Calling OnClick() twice causes OnClick to not work

I have a table of cells, when a cell is clicked an event is triggered. I want to add cells dynamically so I will call OnClick again on all rows. When I call OnClick for the second time, any cells that have OnClick called twice stop firing any events.

The odd thing is at the event of my OnClick function, if I can "Return;" it works, however it throws an error saying "Return" isn't defined

function initBox() {
    $(".selectable").on('click', function (event) {

        //if its selected already, unselect it
        if ($(this).hasClass('rowHighlightColor')) {
            $(this).removeClass("rowHighlightColor");
            selectedCellList = null;
        }
        else {
            //unselect previous cell
            if (selectedCellList != null) {
                selectedCellList.removeClass("highlighted");
            }
            selectedCellList = $(this);

            $(this).addClass("rowHighlightColor");
        }
        Return;
    });
}

Answers


You are adding multiple event handlers to existing cells. This is one reason why I prefer to use just the plain old .onclick property.

Anyway, to solve this issue you can either only apply the event to the new cells, or add an attribute to them when you do add an event, then check that attribute before adding the event again.


it needs to be return instead of Return (capital R)

however, writing return; returns undefined so you can just omit it.

edit:

you attach the event twice, make sure only to attach it once, else it causes (as you noticed) undesired behaviour like attaching class and immediately removing it again.

The reason why it works with "Return" is that the function is only run once because it throws an error when reaching it.

Use jQuerys .live() (or .on() for newer versions, as live is deprecated there) to automatically attach the click event to every new row you add. jQuery live Docs


Need Your Help

How to convert 0 (and only 0) into my data structure

c++ types typeconverter

I am implementing a SI unit type system. To ensure units don't leak in and out, I don't want implicit conversion of any values to a unit, and vice-versa. However, it would be really convenient to b...

Autoheight iFrame Safari Bug

jquery iframe safari resize height

I use jquery to auto resize the height of the iframe based on the content. It works perfect in Firefox but in Safari it gives me always the wrong height (150px).