How can I trigger a function when I click anywhere on my page except on one div (id=menu_content
) ?
This question is related to
javascript
jquery
html
triggers
click
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
});
I know that this question has been answered, And all the answers are nice. But I wanted to add my two cents to this question for people who have similar (but not exactly the same) problem.
In a more general way, we can do something like this:
$('body').click(function(evt){
if(!$(evt.target).is('#menu_content')) {
//event handling code
}
});
This way we can handle not only events fired by anything except element with id menu_content
but also events that are fired by anything except any element that we can select using CSS selectors.
For instance in the following code snippet I am getting events fired by any element except all <li>
elements which are descendants of div element with id myNavbar
.
$('body').click(function(evt){
if(!$(evt.target).is('div#myNavbar li')) {
//event handling code
}
});
try this
$('html').click(function() {
//your stuf
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
you can also use the outside events
here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.
$('html').click(function(e){
if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
// clicked menu content or children
} else {
// didnt click menu content
}
});
my actual code:
$('html').click(function(e){
if (e.target.id != 'datepicker'
&& $(e.target).parents('#datepicker').length == 0
&& !$(e.target).hasClass('datepicker')
) {
$('#datepicker').remove();
}
});
Source: Stackoverflow.com