Pearl
Pearl

Reputation: 9435

How to exclude the elements on Document click

jQuery

$(document).click( function () {
    alert("hi");
}

HTML

<div id="wrapper">
  <div id="inner-1">
    <div id="sub-inner1">Sub Inner1 Content</div>
    <div id="sub-inner2">Sub Inner2 Content</div>
    <div id="sub-inner3">Sub Inner3 Content</div>
  </div>

  <div id="inner-2" style="float:left; width:49%; border:dotted #CC3300;"> 
    content inside inner-2 div 
  </div>
</div>

I want to show the Hi alert message on the Document click using Jquery. But I want to exclude the Inner-1 div and also its children. I meant that I want to get the alert message only when I click on the divs other than inner-1 and its children. Thanks.

Upvotes: 3

Views: 3053

Answers (5)

Rituraj ratan
Rituraj ratan

Reputation: 10378

$(document).not('#inner-1').click(function () {
alert("hi");
});

reference .not()

Upvotes: 0

Vin.AI
Vin.AI

Reputation: 2437

Simply bind a new event to excluding element like this:

jQuery(document).on('click', function(e) {
  alert('Document got a click event');
});

// Here bind event on those event on which you want to exclude from
// document click
jQuery(document).on('click', '#inner-1', function(e) {
  e.preventDefault();
  e.stopPropagation();
  return false;
});

Upvotes: 1

Shailesh Rathod
Shailesh Rathod

Reputation: 106

Please check out this one.

$(document).on("click", "#wrapper > div[id!='inner-1']", function(){
    alert("Hi");
});

I hope this will help you.

Upvotes: 0

Sergio
Sergio

Reputation: 28837

Try this:

$('#wrapper>div').not('#inner-1').click( function () {
    alert("hi");
});

Demo here

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$(document).on('click', function (e) {
    if($(e.target).closest('#inner-1').length == 0){
        console.log("click", e.target);
    }
});

Demo: Fiddle

Upvotes: 3

Related Questions