I want to do something clicking on body
, except on menutop
which is inside the body
.
<body>
<div id="menutop">lorem ipsum...</div>
...
</body>
js
$("body").not($("#menutop")).click(function(){
console.log("323");
});
also tried
var n = $("#menutop");
$("body:not(n)").click(function(){
console.log("323");
});
but clicking on menutop
in both cases console shows 323
We will handle click event of whole body, and then identify the source element of event as below
We will ignore event triggered for above two cases and perform required operations for rest triggered events.
$("body").click(function(event){
if(
document.getElementById("menutop").isSameNode(event.target)
|| document.getElementById("menutop").contains(event.target)
){
// Event triggered from within the #menutop div element
// Do nothing and return
return;
}
// We are here because click event triggered from outside of #menutop div element
alert('Click event triggered from outside of #menutop div element');
});
You can use event.stopPropagation()
on the menutop element to prevent click through to the body below.
See this codepen for the solution
JS
$("body").click(function(){
alert("323");
});
$("#menutop").click(function(event) {
event.stopPropagation();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With