jQuery.unbind()
Join the DZone community and get the full member experience.
Join For FreeBinding Problems
Typically in jQuery when you bind an HTML element with some event this event is fired every time the user (client) triggers it. Thus when you’ve a click event attached on a button you can click it as many times as you want. In some rare cases this can be tricky. Let’s imagine the following scenario.
- The user clicks on a “vote” button.
- Some AJAX calls are performed.
- After a successful AJAX call you setup a cookie to deny further votes from this machine.
This seems to be pretty well known scenario, but as the click event
is attached to the button there is enough time to click several times on
the “vote” button and to vote several times. In this case before the
cookie is set the user can vote more than once.

Demo
So one possible solution is to unbind the click event. In jQuery terms this is done by …
$.unbind()
With this method you can simply unbind the “click” event or whatever event there is attached on the desired HTML element. So now in the first case we had:
$(document).ready(function() { $('input').click(function() { $.ajax({ url : 'http://stoimen.com/projects/jquery.unbind/example1.php' , success : function() { $('p').append('You\'ve voted successfully!<br />'); } }); }); });
Now you can replace the code above with:
$(document).ready(function() { $('input').click(function() { $('input').unbind(); $.ajax({ url : 'http://stoimen.com/projects/jquery.unbind/example1.php' , success : function() { $('p').append('You\'ve voted successfully!<br />'); } }); }); });
As you can see on the demo here now the button cannot be clicked more than once.
Demo

Cookies + unbind()
There is a problem however. After reloading the page the event is attached again, so the user can click on the button once more. The obvious solution is to combine both the cookie and the unbind() as shown in the following pseudo code.
$(document).ready(function() { if (cookie is not set) { $('input').click(function() { $('input').unbind(); $.ajax({ url : 'http://stoimen.com/projects/jquery.unbind/example1.php' , success : function() { $('p').append('You\'ve voted successfully!<br />'); set cookie } }); }); } });
Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments