Follow this Blog!

Jul 5, 2013

f Comment

jQuery: How Do You Bind a Handler to an Event From Scratch?

Amazon Most of us who use jQuery know we can easily bind a handler to some event through jQuery such as the following.
$('#someSelector').click(function(event) {
  alert('I am clicked');
});
The trouble is as you bind more handlers to the same event all these handlers are chained to this event. For example if you do the following.
$('#someSelector').click(function(event) {
  alert('I am clicked');
});
$('#someSelector').click(function(event) {
  alert('I am clicked AGAIN');
});
When #someSelector is clicked you'll see two alert windows. How do you start binding new handlers to the same event from scratch so that only the latest attached handler is called when the said event occurs?

Funny that I could not find the answer to this question on Google.
Solution
It turns out there's a simple solution. Simply call unbind() with the corresponding event before you bind a handler to an event. Here's some sample code.
$('#someSelector').unbind('click');
$('#someSelector').click(function(event) {
  alert('I am clicked');
});
This code will ensure that only the last bound handler is called when the click event happens. This works for any event like mouse over, mouse hover, mouse leave, and so on.

Related article: jQuery: How to Unbind And Rebind Event Handlers?

Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
Find Michael on Google or Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael