Search code examples
jqueryunbind

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?


Solution

  • 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>