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 ?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.
One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.
Selected answer works for one drop down menu only. For multiple solution would be:
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.
Demo: http://jsbin.com/umubad/2/edit
how to have a click event outside of the dropdown menu so that it close the dropdown menu ? Heres the code
Another multiple dropdown example that works https://jsfiddle.net/vgjddv6u/
Stopping Event Propagation in some particular elements ma y become dangerous as it may prevent other some scripts from running. So check whether the triggering is from the excluded area from inside the function.
Here function is initiated when clicking on document, but it excludes triggering from #menucontainer. For details https://css-tricks.com/dangers-stopping-event-propagation/