0

How can I execute code when I change page with the .changePage() function?

For example I use this code:

$.mobile.changePage( "index.html#pageTwo" );

And when pageTwo is loaded I want to do this:

alert("Test");
Sinan Samet
  • 6,432
  • 12
  • 50
  • 93

1 Answers1

1

In your <head> .. </head> put this:


// Jquery loaded here

<script>
    $(document).on("pageshow","#pageTwo", function() {
        alert("Test");
    }
</script>

// jquery mobile loaded here

Notes:

  1. The code above must be placed AFTER Jquery is loaded and BEFORE jquery mobile is loaded.

  2. The code example above assumes that your index.html page contains a div with at least the attributes of data-role="page" and id="pageTwo":

    <div data-role="page" id="pageTwo"> This is page two content </div>

  3. Jquery mobile only parses/uses anything in the <head>..</head> section of the FIRST PAGE THAT IS LOADED! To ensure that all of the code required for all pages in your mobile site are loaded, regardless of which page the user lands on first, you should structure all your pages like this:

    <html>
    <head>
       <script src="path/to/jquery.js"> // load jquery
       <script src="path/to/common.js"> // all jquery mobile page event bindings are placed in here
       <script src="path/to/jquery_mobile.js"> // load jquery mobile
    </head>
    <body>

    <div data-role="page" id="pageOne"> This is page one content </div>

    <div data-role="page" id="pageTwo"> This is page two content </div>

    </body>
    </html>

Drew
  • 4,215
  • 3
  • 26
  • 40
  • 1
    `mobileinit` should be placed before JQM only. The rest should be loaded after JQM. Note that `pageshow` As well as page events are deprecated as of 1.4 ;) – Omar May 02 '14 at 14:53
  • @omar Good point. This is the structure I use with JQM 1.3.1 and it works without error. – Drew May 02 '14 at 14:57