Reputation: 15
Please see this HTML code:
<div class="grid">
<h2>First</h2>
<p>Second</p>
</div>
<div class="grid">
<h2>First</h2>
<p>Second</p>
</div>
I was able to change order of elements on page load with this code:
$('.grid').each(function(){
var p = $(this).find('p'),
h2= $(this).find('h2');
h2.insertAfter(p);
});
But there is more content coming with an ajax pagination so I wrapped that inside $(document).ajaxComplete(function(){
Problem now is my code runs only after the ajax content is loaded, I want my code to run on both page load and on ajax loaded content.
Thank you for your assistance.
https://jsfiddle.net/j0fozshv/2/
Upvotes: 0
Views: 556
Reputation: 5354
You could extract the stuff you need to do multiple times into a function:
function doMyStuff() {
$('.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):
function doMyStuff(data) {
// do what you need
}
And again for your AJAX stuff:
$.get( "/get_some_data", function( data ) {
doMyStuff(data);
});
Upvotes: 1
Reputation: 723
You can make a method like below and call twice, one after page load and one after ajax complete.
// After page load
insertDom();
function insertDom(){
$('.grid').each(function(){
var p = $(this).find('p'),
h2= $(this).find('h2');
h2.insertAfter(p);
});
}
$(document).ajaxComplete(function(){
// Do your work
insertDom();
});
Upvotes: 0