19

Suppose I want to run some code once jQuery Mobile has finished rendering the UI. The mobileinit event doesn't work since it's raised before this happens. A quick Google search seems to indicate that simply using $(document).ready won't work with JQM; but I just tried it (called after mobileinit) and it worked for me: my code ran and dynamically updated elements, etc. just fine. So I'm wondering, is there some reason I shouldn't be using it (it's unreliable or messes up JQM), or is the information out there about it not working simply inaccurate? What am I missing?

Update: See here for a demonstration.

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • 1
    have you checked http://stackoverflow.com/questions/5622581/jquery-mobile-document-ready-equivalent ? – Emil Condrea Jul 28 '11 at 19:09
  • @George: Yes, and according to that question `$(document).ready` *doesn't* work. But strangely, for me, it does. So I guess I'm just trying to figure out if it just works now, or if there are some weird gotchas when dealing with JQM that I should know about. – Dan Tao Jul 28 '11 at 19:19

1 Answers1

12

Most likely the reason you read that $(document).ready won't work with jQuery Mobile is that it does not fire each time you view a pseudo-page. That said, it still triggers as it should when the html document is loaded.

If you want to run code that triggers each time you view a pseudo-page you can use this code:

$('[data-role="page"]').live('pageshow', function () {
    //run your code here
});

NOTE: there are other hooks that you can bind to as well (pageshow, pagehide, pagebefoershow, pagebeforehide), documentation can be found here: http://jquerymobile.com/demos/1.0b1/docs/api/events.html

---------- EDIT ----------

I was thinking about this and the best analog to $(document).ready() is not binding to the "pageshow" event, it would be binding to the "pagecreate" event. $(document).ready() fires once per page load, and "pagecreate" does the same for pseudo-pages whereas "pageshow" fires each time a page is displayed.

So if a user clicked away from the home-screen and then clicked a back button to return to the home-screen, "pageshow" would fire on this second (and subsequent) "showing" of the home-screen.

Also, "pageshow" requires the user to navigate to the page to which it is bound.

Jasper
  • 75,717
  • 14
  • 151
  • 146
  • Ah, I see; so the idea that it "doesn't work" was all along based on a misunderstanding? It's funny; I saw these alternative approaches and thought they were *less than ideal* because they caused an event to fire before each pseudo-page is shown rather than just once for the entire document (i.e., jQuery mobile site). Whereas the latter is precisely what I want. – Dan Tao Jul 28 '11 at 19:48
  • @jasper you're linking to the alpha version api events, best to use beta version – Phill Pafford Jul 28 '11 at 22:03