jQuery Mobile Framework

Navigation Search

Question:

Why isn't DOM ready working for my scripts?

Answer:

One of the first things people learn in jQuery is to use the $(document).ready() function for executing DOM-specific code as soon as the DOM is ready (which often occurs long before the onload event). However, in jQuery Mobile site and apps, pages are requested and injected into the same DOM as the user navigates, so the DOM ready event is not as useful, as it only executes for the first page. To execute code whenever a new page is loaded and created in jQuery Mobile, you can bind to the pageinit event.

The pageinit event is triggered on a page when it is initialized, right after initialization occurs. Most of jQuery Mobile's official widgets auto-initialize themselves based on this event, and you can set up your code to do the same.


$( document ).delegate("#aboutPage", "pageinit", function() {
  alert('A page with an id of "aboutPage" was just created by jQuery Mobile!');
});

If you'd like to manipulate a page's contents before the pageinit event fires and widgets are auto-initialized, you can instead bind to the pagebeforecreate event:


$( document ).delegate("#aboutPage", "pagebeforecreate", function() {
  alert('A page with an id of "aboutPage" is about to be created by jQuery Mobile!');
});
All Questions & Answers