Monday, January 12, 2009

Event Bubbling in JQuery

The scenario: Nested divs representing an outline structure. When the user clicks a heading, the sub-nodes should toggle.

The code would look something like this:


$(".OutlineHeading1 > label").click(function(){
$(this).nextAll(".OutlineHeading2").toggle('slow');
});
$(".OutlineHeading2 > label").click(function(){
$(this).nextAll(".OutlineHeading3").toggle('slow');
});
$(".OutlineHeading3 > label").click(function(){
$(this).nextAll(".OutlineHeading4").toggle('slow');
});
$(".OutlineHeading4 > label").click(function(){
$(this).nextAll(".OutlineHeading5").toggle('slow');
});
$(".OutlineHeading5 > label").click(function(){
$(this).nextAll(".OutlineHeading6").toggle('slow');
});


The problem: In Internet Explorer, the click event gets fired multiple times in the nested divs because of event bubbling.

The solution: return false. As in:

$(".OutlineHeading1 > label").click(function(){
$(this).nextAll(".OutlineHeading2").toggle('slow');
return false;
});
$(".OutlineHeading2 > label").click(function(){
$(this).nextAll(".OutlineHeading3").toggle('slow');
return false;
});
$(".OutlineHeading3 > label").click(function(){
$(this).nextAll(".OutlineHeading4").toggle('slow');
return false;
});
$(".OutlineHeading4 > label").click(function(){
$(this).nextAll(".OutlineHeading5").toggle('slow');
return false;
});
$(".OutlineHeading5 > label").click(function(){
$(this).nextAll(".OutlineHeading6").toggle('slow');
return false;
});


Simple as that.