I have a list item (#planAdminMenuItem
) that has an onclick
attribute. This list item has an icon inside of it (.spinner
) that will collapse #collapseExample
. Whenever the .spinner
is clicked, I want it to run bootstrap collapse only. I do not want it to run drawPlanAdmin
function. I have tried adding event.stopPropagation to my toggleSpinnerLeftMenu
function, but whenever I do that, it also stops the bootstrap collapse. The parent click is blocked, but so is bootstrap collapse.
THE PHP & HTML CODE
<ul> <li id="planAdminMenuItem" onclick="plan.drawPlanAdmin();"> Book Plan <span class="icn icn-chevron-down spinner" onclick="ui.toggleSpinnerLeftMenu(this,event);" data-toggle="collapse" data-target="#collapseExample" data-aria-expanded="true" aria-controls="collapseExample"></span> </li> <!-- the collapsable area --> <li id="collapseExample" class="collapse in"> <ul> <li onclick="plan.drawRunListAdmin();"> Run List View </li> <li onclick="plan.drawLadderAdmin();"> Ladder View </li> </ul> </li> </ul>
THE JS CODE
toggleSpinnerLeftMenu:function(el,event){ el = jQuery(el); if(el.hasClass('icn-chevron-up')){ el.addClass('icn-chevron-down'); el.removeClass('icn-chevron-up'); }else if(el.hasClass('icn-chevron-down')){ el.addClass('icn-chevron-up'); el.removeClass('icn-chevron-down'); } event.stopPropagation(); //why is this stopping the collapse also? },
Advertisement
Answer
stopPropagation
is doing exactly what it is meant to do.
If you want the parent element to be propagated by the click on the inner element then simply don’t do event.stopPropagation
at all.
Though for some reasons if you need to have that then my suggestion is: call the function like
toggleSpinnerLeftMenu:function(el,event){ el = jQuery(el); if(el.hasClass('icn-chevron-up')){ el.addClass('icn-chevron-down'); el.removeClass('icn-chevron-up'); }else if(el.hasClass('icn-chevron-down')){ el.addClass('icn-chevron-up'); el.removeClass('icn-chevron-down'); } plan.drawPlanAdmin(); // Call the function inside of the child element's click handler. event.stopPropagation(); //why is this stopping the collapse also? },
Update: Since you described the issue more clearly in the comment, which has a solution completely south of what I’ve written above, I am updating with the new content that may be able to help.
Instead of attaching two event handlers, one using an inline onClick
attribute and another using Bootstrap’s data-collapse
, use one:
$(".spinner").on("click", function(event) { // tip: Give a better id or class name $('#collapseExample').collapse({toggle: true}); ui.toggleSpinnerLeftMenu(this, event); });
This is the general idea of doing this, you may still have to make some adjustments to your method calls to fit it in.