Sune
Sune

Reputation: 109

jquery and selectors

I want to have a click event on the body tag, but I have a div under the body tag which i dont want to have the click event on. I have tryed with this but that doesent seem to work correct:

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

The html:

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

Upvotes: 2

Views: 126

Answers (2)

David
David

Reputation: 19667

Try


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

Upvotes: 1

jes5199
jes5199

Reputation: 18913

Click events bubble up. The default click handler on InnerDiv delegates to the click event of its parent. You can override that event and ask it not to bubble up.

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

Upvotes: 5

Related Questions