DuchSuvaa
DuchSuvaa

Reputation: 676

jquery: unbind a specific function leaving the other one

I have a simple question: i have two different functions binded to click event:

$("#selector").click(function one() {
// stuff
});

$("#selector").click(function two() {
// other stuff
});

I want to unbind only one of them. How do i do that?

Upvotes: 0

Views: 127

Answers (2)

Robdll
Robdll

Reputation: 6255

The off function is what you are looking for

The .off() method removes event handlers that were attached with .on()

Upvotes: 0

davidgiesemann
davidgiesemann

Reputation: 1000

You need to save the bound functions into variables. After that you can unbind them using jQuery's .off()-method:

(function($){

  var alert1 = function(){
    alert('1');
  }, alert2 = function(){
    alert('2');
  };
  
  // Bind alert1
  $('button').on('click',alert1);
  
  // Bind alert 2
  $('button').on('click',alert2);
  
  // Unbind alert2
  $('button').off('click',alert2);

})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>Alert</button>

Upvotes: 2

Related Questions