jQuery Mobile FAQ

This is a howto FAQ that will cover problems I encounter in my work or on the net and get them solved. Send me yours if you want to. I will credit authors in their howtos.

How do I make JQM work with content I add to DOM? (after a getJSON or stuff)

Since jQuery Mobile beta2 there is a new event create. You trigger this event on the topmost element that you just inserted to DOM. You can also trigger it on the element you appended the data to except some cases when it's a certain part of a widget.
        $.get('data.html',function(data){
					$('#something').append(data).trigger('create');
					},'html');
        

The old way - before beta2

Background: When creating JQM dictionary I decided to store info in json format and load it with an AJAX call. Loaded data is wrapped in some nice html with JQM specific markup. When I add that to DOM it still looks nasty.

Research: I found a lot of issues like this, but they all mentioned working with single elements. And I want a general solution.

Solution: CaffeineFueled suggested calling .page() on a page one adds the content to. It should redraw the whole thing. But it does nothing... After some experiments I found out that .page() can't be called twice for an element. And that's it. To make it work - create a wrapping element, put content in it and when DOM modifications are finished - call .page() on your newly added element.

Example: Short example code assuming there is a file some.stuff and it returns html for some collapsibles.

  $.get('some.stuff',function(data){
    $('#somepage').html('<div data-role="collapsible-set" id="newstuff"></div>');
    $("#newstuff").html(data).page();
   },'html');
          

Conclusion: easy ;)

-naugtur

Why didn't my script run on a subpage?

Pages are loaded via AJAX. If you put a script in the head of the document, it won't run. Also - there is no DOMready event when a subpage is loaded.

Solution: Put the script tag inside the <div data-role="page"> or bind to pagebeforeshow event for that page you want it to work with.

-naugtur
about Contribution welcome!