Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Binding and Unbinding Live Click Events

So there are two constraints to my question:

  1. I must use an external function call in my click event, and
  2. I must use a live click event, rather binding a typical click event.

So my problem is that I'm trying to unbind a click event after it occurs, and then rebind it once the click event code is complete. I'm doing this to prevent duplicate clicks while code is currently in process (I have fadeIn/Out animation that will allow the button to be clicked twice or three times rapidly, thereby executing my code 2 or 3 times, which is nto desired). The code I'm using is below:

$item.live("click", handleClick);

and

function handleClick(ev) {

    $(this).die("click");

    // perform code here, including things with 'ev'

    $(this).live("click", handleClick);
}

Am I crazy, or should this be working with no problems? Right now, I can click once, but not again afterward. So clearly the die() is working, but it's not being re-bound for some reason to that function. I have verified that it does reach the code in handleClick() to re-bind the live click.

Any ideas? Any help would be greatly appreciated. Thanks.

like image 776
MegaMatt Avatar asked Nov 25 '09 19:11

MegaMatt


People also ask

How do you unbind a click event?

jQuery unbind() MethodUse the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.

What is bind and unbind in jQuery?

jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.

How do I check if an element has a click event?

You can inspect by feeding the object reference ( not the jQuery object though ) to $. data, and for the second argument feed 'events' and that will return an object populated with all the events such as 'click'. You can loop through that object and see what the event handler does.


2 Answers

According to the documentation:

Live events currently only work when used against a selector.

$(this) is not a selector.

like image 181
Greg Avatar answered Oct 10 '22 14:10

Greg


To unbind the click handlers from all that were bound using .live(), use the .die() method:

$(".clickme").die("click");
like image 25
Dawjan Avatar answered Oct 10 '22 14:10

Dawjan