views:

74

answers:

2

When I use this code with an element whose id is "foobar":

$("#foobar").click(function () { alert("first"); });
$("#foobar").click(function () { alert("second"); });

I get two alerts: "first" and "second" second.

How do I specify a click event that also clears out any previous click events attached to the element? I want the last $("#foobar").click(...) to erase any previously bound events.

+3  A: 
$("#foobar").click(function () { alert("first"); });
$("#foobar").unbind('click').click(function () { alert("second"); });

Notice the unbind() method. It does exactly what it sounds like.

alex
+10  A: 

You can unbind the events already attached to that element, and then attach the second event handler, so it will be the only one (note the unbind method).

$("#foobar").unbind("click").click(function() { alert("second"); });
GlenCrawford