How to off (Jquery) bind or unbind specific event from any element

1.2k views Asked by At

I want to know how to bind or unbind specific event from any element.

$(document).ready(function(){
  $("#div2").on("click",function(){
    $("#div1").on("click",function(){
      console.log("binded from div2");
    });
  });
  $("#div1").on("click",function(){
    console.log("main document click binded");
 })
  $("#div3").on("click",function(){
    $("#div1").off("click");
  });
})
#div1{
  height:100px;
  width:100px;
  background-color:black;
  color:white;
}

#div2{
  height:100px;
  width:100px;
  background-color:white;
  border:1px solid black;
}

#div3{
  height:100px;
  width:100px;
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="div1">div1
</div>
<br/><br/><br/>

<div id="div2">div2
</div>
<br/><br/><br/>

<div id="div3">off
</div>

Please check attached code snippet.

In it, I have bind an event to div1 initially. Then, I have bind another event to the same div when clicked on div2 so now there are two events to be fired for div1 click.

Now, when I click on div3 to unbind event the .off method will unbind all previously attached event to div1.

My Question is

How can I unbind (using Jquery .off) only one event (let's say second event) from div1 when I click div3.

I have heard that we can name any method to .on or .off from any part of the application but not sure how to apply exactly.

1

There are 1 answers

1
Robin Mackenzie On BEST ANSWER

You can add/ remove individual events by passing functions in/ out of the on and off functions.

In this example the red <div> will remove the second event handler (i.e. the one you added when you click on the white <div>):

$(document).ready(function() {
  $("#div2").on("click", function() {
    $("#div1").on("click", foo2);
  });
  $("#div1").on("click", foo1)
  $("#div3").on("click", function() {
    // turn off the handler for foo2 but keep the handler for foo1
    $("#div1").off("click", foo2);
  });
})

function foo1() {
  console.log('1st event happened');
}

function foo2() {
  console.log('2nd event happened');
}
#div1 {
  height: 100px;
  width: 100px;
  background-color: black;
  color: white;
}
#div2 {
  height: 100px;
  width: 100px;
  background-color: white;
  border: 1px solid black;
}
#div3 {
  height: 100px;
  width: 100px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="div1">div1
</div>
<br/>
<br/>
<br/>

<div id="div2">div2
</div>
<br/>
<br/>
<br/>

<div id="div3">off
</div>