'Click Function Firing More Than Expected
I have an accordion that's hidden until a button is clicked. The accordion is a collection of li(each of which contains a div) that are created dynamically. Here is what the jQuery code looks like:
function accordion() {
var allPanels = $('#navlist li .panel');
var id = 0;
allPanels.hide();
$('#navlist li a').on({
'click' : function(e) {
var selectedPanelID = $(this).parent('li').attr('id');
jQuery.each($('#navlist li'), function(i, panel) {
if(panel.id === selectedPanelID)
$(panel).find(".panel").toggle('slow');
else
$(panel).find(".panel").slideUp('slow');
});
}
});
}
The first time I click the button that shows the accordion everything works fine. However the second time I click the button it seems like this part of the code executes multiple times (the more the button is clicked the more times this code runs. Almost as if the click event is looping):
'click' : function(e) {
var selectedPanelID = $(this).parent('li').attr('id');
jQuery.each($('#navlist li'), function(i, panel) {
if(panel.id === selectedPanelID)
$(panel).find(".panel").toggle('slow');
else
$(panel).find(".panel").slideUp('slow');
});
}
I thought it was due to event bubbling but it does the same thing even if I add either of the following to the code:
return false, e.preventDefault, e.stopPropagation
Any thoughts as to why?
Solution 1:[1]
After researching a bit more the issue appears to be that the event was bubbling. Using e.stopImmediatePropagation() solved the problem although I don't understand why return false , e.preventDefault(), or e.stopPropagation()didn't work. Here is where I add that line of code.
'click' : function(e) {
var selectedPanelID = $(this).parent('li').attr('id');
jQuery.each($('#navlist li'), function(i, panel) {
if(panel.id === selectedPanelID)
$(panel).find(".panel").toggle('slow');
else
$(panel).find(".panel").slideUp('slow');
});
e.stopImmediatePropagation();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | webDev |
