Search code examples
javascriptjqueryajaxsettimeoutdynamic-loading

Dynamically reload elements and read their new attributes in JQuery


I have an Ajax call that returns a piece of html code that is supposed to replace old html code on the page, giving them new attributes. After I successfully dynamically change my elements, I want to run another piece of JS code that reads and uses some of the attributes of the dynamically reloaded elements. However, JS prefers to read the old data (as if it's running synchronously).

The only workaround I've found is to set a timer, but the timer's delay time has to be relatively high (300 ms) to guarantee that it's always done correctly. What is the right way to do this?

Here is a pseudo-code for what I have right now. It works but the 300ms delay time is terrible.

$.post( "ajax/test.html", function( newCode ) {
    $("#myDynamicDiv").html(newCode);
    setTimeout(function(){
        //Use the data that was just stored in #myDynamicDiv
    },300);
});

Solution

  • For me I use .promise().done() may be it'll work with you

    $("#myDynamicDiv").html(newCode).promise().done(function(){
      // your code here
    });
    

    Edit: To someone who'll comes here later ..While my code isn't working with Mohasen he find a solution himself .. Please find his answer below