Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-register events with jQuery

Tags:

jquery

I have been adding new elements via jQuery in some of my projects, and I have stumbled across a bit of a cumbersome issue.

Consider the following:

$('span.claim').click(function() {
    $(this).parent().html('<span class="unclaim">Unclaim</span>'):
});

$('span.unclaim').click(function() {
    $(this).parent().html('<span class="claim">Claim</span>'):
});

And the following markup...

<ul>
    <li><span class="claim">Claim</span></li>
    <li><span class="unclaim">Unclaim</span></li>
    <li><span class="claim">Claim</span></li>
    <li><span class="unclaim">Unclaim</span></li>
</ul>

Unfortunately, after the initial event is fired, no subsequent events are handled.

I realize I could completely restructure and use the .bind() function, but because of the complexity of my project this isn't really all that feasible.

How would I go about re-binding the events after the new elements are created without ditching my anonymous functions, or is it even possible?

like image 559
Skudd Avatar asked Feb 27 '23 20:02

Skudd


2 Answers

You probably want to look at jQuery live events: http://docs.jquery.com/Events/live

Update:

As mentioned on the above page:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

like image 139
Paddy Avatar answered Mar 11 '23 05:03

Paddy


Option 1:

$('a.claim').click(function() {
    $(this).html('Unclaim').addClass('unclaim').removeClass('claim');
});

$('a.unclaim').click(function() {
    $(this).html('Claim').addClass('claim').removeClass('unclaim');
});

Option 2:

function bindClaim(){
$('a.claim').unbind('click').click(function() {
    $(this).parent().html('<span class="unclaim">Unclaim</span>');
    bindUnclaim();
});
}

function bindUnclaim(){
$('a.unclaim').unbind('click').click(function() {
    $(this).parent().html('<span class="claim">Claim</span>');
    bindClaim();
});
}

bindClaim();
bindUnclaim();

Option 3 (recommended):

http://docs.jquery.com/Events/live instead of bind.

like image 21
mauris Avatar answered Mar 11 '23 04:03

mauris