Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click anywhere in the page except on 1 div

How can I trigger a function when I click anywhere on my page except on one div (id=menu_content) ?

like image 958
Vincent Roye Avatar asked Sep 30 '12 13:09

Vincent Roye


People also ask

How do I hide a div by clicking anywhere on the page?

$(document). click(function (event) { $('#myDIV:visible'). hide(); });

How do you hide a div when the user clicks outside of it Javascript?

To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.

How do I close the menu when I click outside?

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.


2 Answers

You can apply click on body of document and cancel click processing if the click event is generated by div with id menu_content, This will bind event to single element and saving binding of click with every element except menu_content

$('body').click(function(evt){            if(evt.target.id == "menu_content")           return;        //For descendants of menu_content being clicked, remove this check if you do not want to put constraint on descendants.        if($(evt.target).closest('#menu_content').length)           return;                     //Do processing of click event here for every element except with id menu_content  }); 
like image 76
Adil Avatar answered Oct 04 '22 14:10

Adil


See the documentation for jQuery Event Target. Using the target property of the event object, you can detect where the click originated within the #menu_content element and, if so, terminate the click handler early. You will have to use .closest() to handle cases where the click originated in a descendant of #menu_content.

$(document).click(function(e){      // Check if click was triggered on or within #menu_content     if( $(e.target).closest("#menu_content").length > 0 ) {         return false;     }      // Otherwise     // trigger your click function }); 
like image 35
nbrooks Avatar answered Oct 04 '22 16:10

nbrooks