Something that tripped me up when I started learning jQuery was how to stop event bubbling on events bound to the document and I searched for a while without much luck. What I wanted to do was create a jQuery dropdown menu based on an unordered list. If a user were to click a trigger, the menu would open, clicking the trigger again would cause it to close; simple enough as the example below illustrates:
Example 1 – Open and close with the same trigger
So far it’s not exactly rocket science: you click the menu heading and it opens – you click it again and it closes! Although this is generally fine, the standard behaviour of most menus is that clicking outside of the menu would ordinarily cause it to close.
In order to replicate this functionality, I need to bind a click event to the document like the example below:
Example 2 – Open and close with trigger and close with document
You’ll notice in the example above that although the menu opens if you click on the panel the menu closes. This is not desired behaviour and it’s caused because the document event we created above is also applied to our dropdown menu.
The way to ensure it works everywhere is to use another click event – this time – applied to the area we don’t want to be able to click:
Example 3 – Using stopPropagation() to prevent event bubbling
The finished code above adds another click event to the panel itself but this time makes use of a nifty attribute which plumbs into the function’s event object (e) and stops the propagation of the click event from going any further. So… to cut a long story short use stopPropagation() to prevent event bubbling.