I'm creating an app with jQuery Mobile with one nav that sits outside of the pages it's controlling (i.e. the nav isn't replicated within each page, only one instance outside of container). The pages are delivered in the 'usual' data-role = "page1" with data-role = "button" links linking to the page id's.
I have page-specific JS for each page that I have within an external JS file set up as a series of if statements - if the target id is page1, run the code, if the target id is page2 run that code etc.
It works perfectly if all the pages only load once, but if I reload the pages (click back on the page via the nav), the code doesn't fire again from the start; it's still in the same state as when the JS finished running on that page the first time (the JS is controlling an animation on each page).
I'm binding the whole of the JS to the pages, but do I need to bind each page's JS to its page? I'm tried in vain to research this - I'm just starting out in jQ M.
Here's my JS:
$(document).bind('pagecreate', function (e) {
if (e.target.id == 'one') {
$('#div-one').animate({marginLeft:"500px"});
}
if (e.target.id == 'two') {
//Perform jQuery .animate function
}
if (e.target.id == 'three') {
//Perform jQuery .animate function
}
//etc
});
Any help or advice would be appreciated!!
In your example pagecreate
event will trigger only once, when page is created for the first time.
So change it to pagebeforeshow
event, like this:
$(document).bind('pagebeforeshow', function (e) {
If you don't know what page event to use always use pagebeforeshow
.
To find out more about page events and how they work take a look at this ARTICLE or find it HERE.
One more thing, this is not an error but bind(..
is deprectaed, switch to on(...
for event binding:
$(document).on('pagebeforeshow', '[data-role="page"]', function (e) {
or if you want to target specific page:
$(document).on('pagebeforeshow', '#page-id', function (e) {