Reputation: 16627
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
Reputation: 38860
So what is happening is that your event is bubbling up the dom.
div2
div2
click function is calleddiv1
div1
div2
click function ends (with an implicit return true
)div1
receives bubbled click eventdiv1
click function is calledif 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
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