AdobeStock_455007340

jQuery Mobile Control Refresh Gotcha

jQuery lets you manually manipulate controls like lists. For example, you can do something like this to add an item to a list:
$('#myList').append('

  • Some text
  • ');
    In jQuery Mobile, if you manually update lists like that, then when you are done you must force the list to refresh so that formatting and styles are applied. To do this, just use:
    $('#myList').listview('refresh');
    But, there is one gotcha you should be aware of. jQuery Mobile apps are usually comprised of pages, each defined with a

    , and often with multiple in the same .html file. jQuery (and thus jQuery Mobile) lets you manipulate any controls in your page, so you can append or change controls in a page not currently being displayed. But, the .listview(‘refresh’) call? That will only work if the control is on the currently displayed page. If you try to .listview(‘refresh’) a control on a page that is not displayed, you’ll see this error:
    Uncaught cannot call methods on listview prior to initialization; attempted to call method 'refresh'
    So, if you do need to update controls on a not currently displayed page, remember to load that page before triggering the refresh.

    4 responses to “jQuery Mobile Control Refresh Gotcha”

    1. Mike Avatar
      Mike

      Hi Ben,
      This is one question that always comes up at the JQM forum so its good to see it spelled out, one thing I would mention though is that while you can have multiple pages in an HTML (multi page template)
      JQM recommends to use the single page template as it is cleaner and more lightweight.
      I know its a little nit picky but I think its important to point out because programs like DW 5.5 give you the basic template that has the page ID’s in it and while it works to do it that way I think its setting developers up to create a web app outside of the recommended method of JQM.
      Anyhow great post!

    2. Ivan R. Avatar
      Ivan R.

      Genius!

    3. Isaac Lim Avatar
      Isaac Lim

      Thank you so much for writing this article! It helped me soo much with debugging my app for school! Thanks!!

    4. Craig Laparo Avatar
      Craig Laparo

      I’m running into this problem as well. You said (and I had suspected) I need to "load" the hidden pages before updating their controls.
      How exactly do you recommend doing this? I’ve tried all kinds of things, and searches have been fruitless. Thanks in advance.

    Leave a Reply