Skip to content Skip to sidebar Skip to footer

Run Js Code On Load And On Ajax Loaded Content

Please see this HTML code:

First

Second

First

&

Solution 1:

You could extract the stuff you need to do multiple times into a function:

functiondoMyStuff() {
  $('.grid').each(function(){
    var p = $(this).find('p'),
        h2= $(this).find('h2');
    h2.insertAfter(p);
  });

  // or do what you need. it's just an example
}

And after that, just use your function where you need. On document ready:

$(function () {
     // ... doMyStuff();
});

If you have AJAX stuff somewhere, just call it for success callback:

// just an example !
$(document).ajaxComplete(function() {
    doMyStuff();
});

One more example with jQuery AJAX:

$.get( "/get_some_data", function( data ) {
  doMyStuff();
});

Maybe it makes sense for that function to take some args (e.g. data that is returned from the server):

functiondoMyStuff(data) {
  // do what you need
}

And again for your AJAX stuff:

$.get( "/get_some_data", function( data ) {
  doMyStuff(data);
});

Solution 2:

You can make a method like below and call twice, one after page load and one after ajax complete.

// After page load insertDom();

functioninsertDom(){
  $('.grid').each(function(){
      var p = $(this).find('p'),
      h2= $(this).find('h2');
      h2.insertAfter(p);
  });
}

$(document).ajaxComplete(function(){
    // Do your workinsertDom();
});

Post a Comment for "Run Js Code On Load And On Ajax Loaded Content"