Search code examples
javascriptajaxjqueryjquery-append

jquery .live() and .append()


So I'm currently using .append() to add a feature to all of the posts on a webpage, but when additional posts are loaded on the page, the appended features aren't included in the new content — I'm trying to come up with a way to make sure all of the new content has the appended feature too.

$(this).append('<div id="new_feature></div>');

Something like this?

$(this).live().append('<div id="new_feature></div>');

Maybe there's a way to make it constantly appending in a loop perhaps?


Solution

  • jQuery documentation:

    Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks.

    You can use setTimeout() function that can check for new <div>s every n milliseconds.

    $(function(){
        setInterval("Check4NewDivs();",1000);
    });
    

    So say this is a div with class="comment newdiv", so when it appears on the page for the first time, it has the class newdiv that will let the function know it was just dynamically created.

    function Check4NewDivs(){
        $(".comment .newdiv").each(function(){
            $(this).append('<div class="new_feature"></div>').removeClass("newdiv");
        });
    }