简体   繁体   中英

how to catch click on page body

I have a page with a number of divs in it and when someone clicks one of them it calls a javascript method. I need to be able to also trigger another method call if someone clicks the body, meaning they didn't click a div but outside the div. When I put a jquery click handler on the body tag it fires even when you click the div. Anyone know how I can restrict the click to anything outside the divs? Thanks.

You need to check the original target of the click event. It is accessible as e.target where e is the click event.

var div = document.getElementById('the-div');

document.body.onclick = function (e) {
  var target = e.target;
  while (target !== document.body) {
    if (target === div) {
      // The user clicked inside the div
      return;
    }
    target = target.parentNode;
  }

  // do the stuff you want when they click outside the div here
};

You can set the onclick callback on the whole document:

document.onclick = function(){
    alert("CLICK");
};

See also JavaScript event delegation

You could make the entire window track click events, where the div, if clicked, will stop event propagation.

<!DOCTYPE html>
<html>
    <head>
        <title></title>

        <style>

            #wrapper {
                position:absolute;
                left:0px;
                top:0px;
                width:100%;
                height:100%;
            }

            #antidiv {
                position:absolute;
                left:40px;
                top:80px;

                width:100px;
                height:100px;

                background-color:#3FF;
            }

        </style>

    </head>
    <body>

        <div id="wrapper">

            <div id="antidiv"></div>


        </div>

        <script>

            document.getElementById("antidiv").addEventListener("click", function(e) {
                e.stopPropagation();
            }, false);

            document.body.addEventListener("click", function(e) {
                alert("You didn't click the div!");
            }, false);




        </script>

    </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM