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

About Author

Author Image
Arun Kumar

Arun is a creative UI Developer

Request for Proposal

Name is required

Comment is required

Sending message..