medihack
medihack

Reputation: 16627

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?

Upvotes: 3

Views: 1203

Answers (2)

Darko
Darko

Reputation: 38860

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");
});

Upvotes: 8

Mitch Malone
Mitch Malone

Reputation: 892

The reason for this is because when you click #div2 you are also tracking a click for #div1. This can be fixed by doing a return false after you change the color for the #div2 click. See this jsFiddle for a working version: http://jsfiddle.net/mitchmalone/UFL7X/1/

$("#div1").live("click", function() {
    $("#div1").css("background-color", "red");
});

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

Upvotes: 3

Related Questions