jQuery Mobile - Events at page transition

By on

jQuery mobile is already pretty good and usable. One has to deal with a lack of documentation (examples are there - but no reference). So it took me to do some testing to understand completely how i could use the events generated by page transition.

Docs tell you how you can get it running.

But if you come across: "Note that all four of these events expose a reference to either the next page (nextPage) or previous page (prevPage), depending on whether the page is being shown or hidden" you might think like me. I don't like the "the one or either reference is filled" things in my coding life. "Sometimes it works, sometimes not". "I might read that book or the other".

I wrote some code in my mobilinit function:

$( document ).bind( "mobileinit", function() {
    $('div[data-role="page"]').live('pagebeforeshow',function(event, ui){
         console.log("pagebeforeshow: " + ui.nextPage + " : " + ui.prevPage);

    $('div[data-role="page"]').live('pagebeforehide',function(event, ui){
         console.log("pagebeforehide: " + ui.nextPage + " : " + ui.prevPage);

    $('div[data-role="page"]').live('pageshow',function(event, ui){
        console.log("pageshow: " + ui.nextPage + " : " + ui.prevPage);

    $('div[data-role="page"]').live('pagehide',function(event, ui){
        console.log("pagehide: " + ui.nextPage + " : " + ui.prevPage);

Please note my selector:


If you use:


as selector all divs in your app will be treated as page. Not very good for your app, believe me.

The output of my script is:

[INFO] pagebeforehide:[object Object] : undefined
[INFO] pagebeforeshow: undefined : [object Object]
[INFO] pagehide: [object Object] : undefined
[INFO] pageshow: undefined : [object Object]

You can see * pagebeforehide and pagehide do always contain a nextPage. * pagebeforeshow and pageshow do always contain a previousPage.

I would have expected that at least pagebeforeshow would have a reference to the nextPage as it is not show (so there actually is a next page to show). pageshow does not have a nextPage because there is only a "current page".

You need to be careful. My iPhone 4.0 emulation stops working when you do the following:

$('div[data-role="page"]').live('pagebeforeshow',function(event, ui){
  console.log(ui.nextPage.attr('id')); // <- nasty, evil stuff

pagebeforeshow does not have that nextPage as already mentioned an so calling attr on an undefined object has frozen my app.

If you would like to do something on a specific next page (before it is shown), you could do something like that:

$('div[data-role="page"]').live('pagebeforehide',function(event, ui){
  var page = ui.nextPage;
  if(page.attr('id') == "myPage) {
      alert("do something");
Tags: JavaScript, jQuery, jQuery mobile