Brett Brett - 1 month ago 7
jQuery Question

Removing certain elements from a selector binded to the body

I have a

click
event binded to the body element but I don't want it to fire for when the user clicks on certain elements, that being when the element has an attribute of
data-dropdown-target
, however what I have tried isn't working, it always fires.

CodePen: http://codepen.io/anon/pen/ORQkrb

HTML:

<body>
<div class="foo">foo</div>
<div class="bar" data-dropdown-target="something">bar</div>
<div class="moo">moo</div>
</body>


CSS:

.foo, .bar, .moo {
padding: 10px;
margin: 5px;
}

.foo {
background-color: gray;
}

.bar {
background-color: teal;
}

.moo {
background-color: green;
}


JS:

$('body').not('[data-dropdown-target]').on('click', function(e) {

console.log('Hi!');

});


I assume this is because it is trying to remove
body
elements that have this attribute, rather than it's children - correct?

How do I go about stopping it from firing on children elements that have this attribute - do I have to loop through everything, as I would like to avoid that because of performance reasons, especially since it's on the body.

Answer

Actually your code try to bind event click on every <body> without data-dropdown-target attribute.

This could solve your problem :

$('body').on('click', function(e) {
    if($(e.target).data('dropdown-target') || $(e.target).parents('[data-dropdown-target]').length !== 0) return false;
    console.log('Hi!');

});
.foo, .bar, .moo {
  padding: 10px;
  margin: 5px;
}

.foo {
  background-color: gray;
}

.bar {
  background-color: teal;
}

.moo {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  
  <div class="foo">foo</div>
  <div class="bar" data-dropdown-target="something">bar</div>
  <div data-dropdown-target="something">
    <div class="moo">moo</div>
  </div>
</body>

Comments