Kaya Toast Kaya Toast - 6 months ago 19
jQuery Question

jquery unbind or off click event handler within specific parent

I have 3 buttons, and all of them have event handlers on click.

If a button is within a specific parent, then there should be no click event on the button. But rather, a click event should exist at that specifc parent level itself.

In the code below, on clicking the button within

.case2
, I was expecting the alert to show "case2 parent clicked", but it still shows the alert "button clicked".

Why is that happening ? And how do I correct it ?

Thanks.



$('.button').on('click', function (e) {
alert('button clicked');
e.stopPropagation();
});


$('.case2')
.off('click', '.button', function (e) {
e.stopPropagation();
})
.on('click', function (e) {
alert('case2 parent clicked');
e.stopPropagation();
});

.case1, .case2, .case3 {
margin:1em;
padding: 1em;
background-color: #0b97c4;
width: 5em;
height:2em;
}

.button {
padding: 1em;
background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="case1">
<div class="button"></div>
</div>
<div class="case2">
<div class="button"></div>
</div>
<div class="case3">
<div class="button"></div>
</div>




Answer

Use :not in the selector.

$('.button:not(.case2 .button)').on('click', function (e) {
    alert('button clicked');
    e.stopPropagation();
});

$('.case2').on('click', function (e) {
    alert('case2 parent clicked');
    e.stopPropagation();
});
.case1, .case2, .case3 {
  margin:1em;
  padding: 1em;
  background-color: #0b97c4;
  width: 5em;
  height:2em;
}

.button {
  padding: 1em;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="case1">
    <div class="button"></div>
</div>
<div class="case2">
    <div class="button"></div>
</div>
<div class="case3">
    <div class="button"></div>
</div>

Comments