Jquery Trigger Event When Click Outside The Element
Solution 1:
Just have your menuWraper
element call event.stopPropagation()
so that its click event doesn't bubble up to the document
.
Try it out:http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
Alternatively, you could return false;
instead of using event.stopPropagation();
Solution 2:
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your divif (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
Solution 3:
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()
) when it came from within a .menuWrapper
element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document
, if it gets there, we hide those .menuWrapper
elements.
Solution 4:
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
Solution 5:
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
Post a Comment for "Jquery Trigger Event When Click Outside The Element"