Shyam
Shyam

Reputation: 2377

Re-attach event to newly loaded div

Apparently my JQuery events die when the elements are replaced. Currently they are attached like this:

$("a[id^='anb']").click(
        function () {
            /* ommited for readability */;
            var furl = "target_view";
            $('#my_article_container').load(furl, function() {
                       animateThem(); });
            return false;
        }

    );

    $("div[id^='art']").hover(
        function() {
            $(this).fadeTo("slow", 0.33);
        }
    );

Is there a mechanisme inside JQuery or a handy work around on how to re-bind these events?

Upvotes: 5

Views: 3224

Answers (6)

Dai Bok
Dai Bok

Reputation: 3616

This was the first answer that came up when I googled it - me having the same problem. Live has been deprecated in version 1.7 and removed in version 1.9. The new versions of JQuery recommend using on. jQuery.on()

Anyway, just to keep this up to date. I the end I got mine to work by including the selector in the on function eg:

$(document).on("click","a[id^='anb']",function(){....})

Upvotes: 5

I believe you're looking for jQuery.live()

Upvotes: 1

You're looking for the .live() function.

This will monitor the dom and reattach events automatically as items are added.

$("a[id^='anb']").live('click',
    function () {
        /* ommited for readability */;
        var furl = "target_view";
        $('#my_article_container').load(furl, function() {
                   animateThem(); });
        return false;
    }

);

$("div[id^='art']").live('hover',
    function() {
        $(this).fadeTo("slow", 0.33);
    }
);

Upvotes: 6

Amr Elgarhy
Amr Elgarhy

Reputation: 68992

Live is your friend

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187134

Use $.live() instead, which is designed to work for this very case.

$("a[id^='anb']").live('click', function() { ... });
$("a[id^='art']").live('hover', function() { ... });

Upvotes: 1

Marek Karbarz
Marek Karbarz

Reputation: 29314

Use the live function instead.

Upvotes: 1

Related Questions