← back to code snippets


jQuery binding tip

Posted on April 30th, 2014 in JavaScript by Graeme

This is a good little trick I’ve just picked up, which allows you to bind multiple functions to the same event (e.g. click), without each of the functions effecting the other.

 

Here’s the scenario. Say there are multiple functions bound to the same click event. For example when you press a button, you have two functions firing as below:

 

 
//click event 1 
$('.button').bind('click', function() { 
    alert("you clicked me!"); 
    }

//click event 2 
$('.button').bind('click', function() { 
   alert("you clicked me again!"); 
   }
    

 

image

 

But what if you only want the first click event to fire on the first time you press the button, and never again? You’d need to unbind the event like so:

 

    
        $('.button').unbind('click');
    

 

The problem is that this would also unbind your other click event! This is not what we want!

 

So here’s a solution I’ve come across. You can add a sort of namespace to the click event! So where you normally bind ‘click’, you can do 'click.fireonce’, or any name you want:

 

    
    //click event 1 
    $('.button').bind('click.fireonce', function() { 
    alert("you clicked me!"); 
    }
    

 

Then when it comes to unbinding, you just unbind the namespaced click, leaving your other function bound:

 

    
       $('.button').unbind('click.fireonce');