Close dropdown menu when clicked outside of it using jquery
Posted By : Arun Kumar | 06-Dec-2015
Closing a dropdown on clicking elsewhere in the page except the dropdown menu is the standard behaviour these days.
But getting to know how can one differentiate if the clicked element is not the dropdown is the real solution to close the dropdown.
lets write a code to show the dropdown.
ex:
html structure
<div class="dropdown-container"> <span>Dropdown</span> </div> <div class="dropdown-menu"> <ul> <li>menu1</li> <li>menu2</li> <li>menu3</li> </ul> </div>
the dropdown menu is set not to be displayed by default with some css.
lets open /close the dropdown using jquery
$(".dropdown").click(function(){
$(this).find('dropdown-menu").toggle();
);
the above code will show or hide the dropdown menu when clicked on dropdown.
but if we want to close the dropdown when the clicked element is not dropdown then we would write something like this:
$("document").on("click",function(event){
if(!$(event.target).closest(".dropdown").length){
//write code to hide the dropdown.
}
});
That's it !
THANKS
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Arun Kumar
Arun is a creative UI Developer