I have a problem understanding a special Javascript event scenario.
For an illustration please see /
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?
I have a problem understanding a special Javascript event scenario.
For an illustration please see http://jsfiddle/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?
Share Improve this question edited Jul 25, 2019 at 16:08 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jan 27, 2011 at 4:37 medihackmedihack 16.6k21 gold badges91 silver badges140 bronze badges2 Answers
Reset to default 8So what is happening is that your event is bubbling up the dom.
- Click occurs on
div2
div2
click function is called- it changes the colour of
div1
- it assigns a click event to
div1
div2
click function ends (with an implicitreturn true
)- event bubbles up to parent in DOM
div1
receives bubbled click eventdiv1
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");
});
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/mitchmalone/UFL7X/1/
$("#div1").live("click", function() {
$("#div1").css("background-color", "red");
});
$("#div2").live("click", function() {
$("#div1").css("background-color", "green");
return false;
});