3

In jQuery mobile, I want to show a dialog message in my homepage (index.html) when this page is first loaded. However, if the user navigates to different pages of my site and comes back to my index.html, I don't want to show show the dialog.

I am thinking about using pageshow or pagebeforeshow method and checking prevPage object. Is there any other good way to do it?

Gajotres
  • 57,309
  • 16
  • 102
  • 130
N Rocking
  • 2,947
  • 2
  • 21
  • 24

2 Answers2

5

Use pageinit event, It will trigger only once. Can't be easier then this.

jsFiddle example: http://jsfiddle.net/Gajotres/e9RcT/

$(document).on('pageinit', '#index', function(){       
    alert('This event will trigger only once!');
});

To test it go to second page and then go back.

Gajotres
  • 57,309
  • 16
  • 102
  • 130
  • The only issue with this approach is it assumes the page will remain cached in the DOM. If `#index` gets flushed, I am pretty sure `pageinit` gets fired again when the page is re-loaded. If this is he case, you will need to employ some type of local storage or cookie to maintain the state of having shown the message. – andleer Feb 08 '13 at 17:50
  • @Gajotres It's a very quick solution. I am also considering andleer's comment. In that case, local storage will be a good solution. Thank you! – N Rocking Feb 08 '13 at 18:11
  • In case you also want to incorporate andleer solution take a look at my other article: http://stackoverflow.com/a/14469041/1848600 , there you will an example of localstorage usage. – Gajotres Feb 08 '13 at 18:28
2

Loading on the DOM will ensure whatever you want to take place only happens on the first page initialization:

$(document).ready(function(){
  // do stuff here
});

source: http://jquerymobile.com/test/docs/api/events.html

Michael Minter
  • 531
  • 4
  • 16
  • Read before you post something. document ready should NOT be used with jQuery Mobile. And regarding pageinit: To execute code whenever a new page is loaded and created, you can bind to the pageinit event. This event is explained in detail at the bottom of this page. – Gajotres Feb 08 '13 at 17:42
  • It's "recommended" NOT enforced as a requirement to using jQuery Mobile. But I see that your answer is also relative. Thanks Gajo – Michael Minter Feb 08 '13 at 18:14
  • @Gajotres If the `document.ready` event handler is only found on the `index.html` page (outside of the `
    ` element) then this will work as desired. The `document.ready` event handler will only fire if the user directly loads or refreshes the `index.html` page. If the user navigates to the `index.html` page after landing on a different page, the event handler will not fire. It seems like this is one case where `document.ready` is actually better than `pageinit` or any other jQuery Mobile event.
    – Jasper Feb 13 '13 at 22:28