I am developing a simple dropdown menu with jQuery . When a user press on a trigger area, it will toggle the dropdown area. My question is how to have a click event outside of the dropdown menu so that it close the dropdown menu ?
Answer: Use the jQuery on() method You can use the jQuery click() method in combination with the on() method to hide the dropdown menu when the user click outside of the trigger element.
To open the dropdown menu, use a button or a link with a class of . dropdown-toggle and the data-toggle="dropdown" attribute. The . caret class creates a caret arrow icon (), which indicates that the button is a dropdown.
You can tell any click that bubbles all the way up the DOM to hide the dropdown, and any click that makes it to the parent of the dropdown to stop bubbling.
/* Anything that gets to the document will hide the dropdown */ $(document).click(function(){ $("#dropdown").hide(); }); /* Clicks within the dropdown won't make it past the dropdown itself */ $("#dropdown").click(function(e){ e.stopPropagation(); });
Demo: http://jsbin.com/umubad/2/edit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With