Jquery and selectors

I want to have a click event on the body tag, but I have a div under the body tag that I don't want to include a click event. I tried with this, but this seems to work right:

$("body").not("#InnerDiv").click(function() {
    alert("Hejhej");
});

      

html:

<body>
   <div id="1">1</div>
   <div id="2">2</div>
   <div id="InnerDiv">InnerDiv</div>
</body>

      

+2


source to share


2 answers


Calls push events. The default click handler on InnerDiv delegates to its parent's click event. You can override this event and ask it not to bubble up.



$("body").click(function() {
          alert("Hejhej");
      });
$("#InnerDiv").click(function(e) {
          e.stopPropagation();
      });

      

+5


source


Try




    $("body").click(function() { alert("Hejhej"); });
    $('#InnerDiv').click(function(e) { e.stopPropagation(); });

      

+1


source







All Articles