jQuery: Binding and Unbinding Live Click Events
Asked Answered
O

3

11

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.

Oleta answered 25/11, 2009 at 19:18 Comment(0)
L
8

According to the documentation:

Live events currently only work when used against a selector.

$(this) is not a selector.

Leander answered 25/11, 2009 at 19:21 Comment(1)
@Greg, interesting. Maybe if I assigned the live click event in the function as such: var $tempVar = $('#' + $(this).attr('id')), and then said $tempVar.live("click", handleClick) Do you think this would work?Oleta
E
6

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

$(".clickme").die("click");
Ecker answered 17/7, 2011 at 13:3 Comment(0)
B
0

You can use this pattern to unbind the clicked element and let all others live:

$('a.myselector').live('click', function() {

    // do things

    $(this).unbind('click').live('click', function() {return false;});

    return false; // block the link
});

works with JQUERY 1.8.2

Brochu answered 4/6, 2013 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.