jQuery Event Handling: Preventing Double Bindings

This post will show you how to deal with situations where event handlers are bound to elements more than once, causing multiple reactions when an event is triggered.

Two solutions will be covered:

  1. Using unbind() to clear previous bindings.
  2. Adding a class to the element after the first binding.

Consider the following snippet that binds a click event to a span tag. Depending on the placement of this snippet, two or more alerts may be spawned.

$("span").click(function () {
  alert("Clicked");
});

The Solutions

Using unbind()...

$("span").unbind("click").click(function () {
  alert("Clicked");
});

or, using addClass()...

// the :not selector prevents the handler from being bound
// to the element a second time since the "processed" class
// is added after the first binding.
//
// note that you may use any class name.
$("span:not(.processed)").click(function () {
  alert("Clicked");
}).addClass('processed');

__________________

Sando George Sando George is a web development freelancer and a budding Computer Science researcher. He also serves as the CTO of Social Capital Holdings, a startup company dedicated to raising funds for charitable and socially responsible organizations.