Search code examples
javascriptjqueryclickmouseeventdom-events

Consecutive click events


I have a problem understanding a special Javascript event scenario.

For an illustration please see http://jsfiddle.net/UFL7X/

When the yellow box is clicked the first time, I would expect that only the first click event handler is called and the large box gets green. But both event handlers are called (the large box gets red), even though the second handler didn't exist by the time the click occurred (at least what I thought).

How can that be explained?


Solution

  • So what is happening is that your event is bubbling up the dom.

    1. Click occurs on div2
    2. div2 click function is called
    3. it changes the colour of div1
    4. it assigns a click event to div1
    5. div2 click function ends (with an implicit return true)
    6. event bubbles up to parent in DOM
    7. div1 receives bubbled click event
    8. div1 click function is called

    if you dont want this to happen then you need to return false in your click handler for div2

    EDIT: Please note that the way you are organising your JS may not be the best because if I click div2 100 times that means that div1 now has 100 click events that will run.

    I suggest that you do it this way (keep in mind that I don't know what your requirements are):

    $("#div2").click(function() {
        $("#div1").css("background-color", "green");
        return false;
    });
    
    $("#div1").click(function() {
        $("#div1").css("background-color", "red");
    });