Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click on body except on specific div

Tags:

jquery

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

like image 397
qadenza Avatar asked Feb 10 '16 23:02

qadenza


2 Answers

We will handle click event of whole body, and then identify the source element of event as below

  • If click event triggered from the target element (#menutop) document.getElementById("menutop").isSameNode(event.target)
  • If click event triggered from any of descendants of target element (#menutop) document.getElementById("menutop").contains(event.target)

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');
});
like image 103
Anil Agrawal Avatar answered Sep 30 '22 19:09

Anil Agrawal


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();
});
like image 29
Carlton Avatar answered Sep 30 '22 17:09

Carlton