Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-attach event to newly loaded div

Tags:

jquery

events

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?

like image 789
Shyam Avatar asked Apr 21 '11 17:04

Shyam


People also ask

How do you add an event listener after an element was created dynamically?

To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .

Can I use onload with Div?

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.

Which method is used to bind a callback method for an event for DOM elements added at runtime?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.


1 Answers

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);
    }
);
like image 153
Richard Marskell - Drackir Avatar answered Oct 04 '22 05:10

Richard Marskell - Drackir