views:

3981

answers:

4

I want to attach an click event to a button element and then later remove it, but I can't get unclick() or unbind() to do anything. In this example below, the button is tan and the click event works.

window.onload = init; 
function init() {
    $("#startButton").css('background-color', 'beige').click(process_click);
    $("#startButton").css('background-color', 'tan').unclick();
}

How can I remove events from my elements?

+1  A: 

unbind is your friend. $("#startButton").unbind('click')

redsquare
+8  A: 

There's no such thing as unclick(). Where did you get that from?

You can remove individual event handlers from an element by calling unbind:

$("#startButton").unbind("click", process_click);

If you want to remove all handlers, or you used an anonymous function as a handler, you can omit the second argument to unbind():

$("#startButton").unbind("click");
Jim
http://www.visualjquery.com/1.0.4.htmlunclick(fn)Removes a bound click event from each of the matched elements. You must pass the identical function that was used in the original bind method.
Edward Tanguay
Thanks for the info. I dug a little deeper, and found that unclick() was removed in jQuery 1.1.
Jim
A: 

Are you sure you want to unbind it? What if later on you want to bind it again, and again, and again? I don't like dynamic event-handling bind/unbind, since they tend to get out of hand, when called from different points of your code.

You may want to consider alternate options:

  • change the button "disabled" property
  • implement your logic inside "process_click" function

Just my 2 cents, not an universal solution.

Filini
A: 

Or you could have a situation where you want to unbind the click function just after you use it, like I had to:

$('#selector').click(function(event){ alert(1); $(this).unbind(event); }

alessioalex