Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content not loading dynamically into DIV using jQuery mobile

This example does not show exactly the problem, just to have an idea. For example when I click on the page 2, the content does not load in the div, I must refresh the page to see the content of the page 2.

P.S : The same code is duplicated in the others pages.

Code :

$(document).ready(function() {
    $('.content-primary').html("Content of page 1"); // This line just in this example
    //$(".content-primary").load("content-of-page.php"); // but I used this code on all my pages 
});
like image 594
Mils Avatar asked Jul 04 '26 18:07

Mils


1 Answers

This is a common jQuery Mobile problem.

You should not use document ready with jQM, instead jQM provides page events. Your problem is document ready who can, and usually triggers before page is loaded into the DOM. That is why refresh helps, at that point page is already loaded.

I made you a working example: http://jsfiddle.net/Gajotres/8hKe2/

$(document).on('pagebeforeshow', '#foo', function(){       
    alert('This is foo');
});

$(document).on('pagebeforeshow', '#bar', function(){       
    alert('This is bar');
});

Basically each page event will trigger javascript code only meant for that page. If you want your code to execute only once, pageinit event should be used instead of pagebeforeshow, like this:

$(document).on('pageinit', '#foo', function(){       
    alert('This is foo');
});

$(document).on('pageinit', '#bar', function(){       
    alert('This is bar');
});

If you want to find more take a look at my other article/answer: https://stackoverflow.com/a/14469041/1848600

like image 132
Gajotres Avatar answered Jul 07 '26 08:07

Gajotres