How to update slider web control on every page visit using JQuery Mobile

330 views Asked by At

I am creating a JQuery Mobile web app and on one page I have javascript that gets values stored in HTML5 local storage and updates web controls on the page with their values. One of the web controls is a slider control.

I need the javascript to execute every time the page is visited so it will update the controls properly from local storage. The only applicable JQuery events I could find that fire at every page are the pageshow and the pagebeforshow events so I tried to tie the code to execute during these events. Example follows:

  var onPageShow = function () {
    // Restore setting values from device browser local storage
    if (localStorage.getItem("mmb_AutoLogin")) {
      $('#AutoLogin').val(localStorage.getItem("mmb_AutoLogin").toLowerCase());
      $('#AutoLogin').slider('refresh');
    }
  };

  $(document).delegate('#maxsettings', 'pageshow', onPageShow);

The problem is that I get an error when trying to reference the slider: 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'slider'

I need to refresh the slider web control after changing its value from default or it will not change visually.

That is the issue. How do I run the script every time the page loads and update the slider web control without getting the error? I feel like I have to jump through hoops to make jQuery Mobile handle something which should be so simple.

2

There are 2 answers

0
Obi Wan On

This is how I solved the issue, in case anyone wants to know how to execute JQuery Mobile code every time a page is visited.

  $(document).ready(function () {
    $('#maxsettings').bind('pageshow', function () {
      // To execute each time page is shown
      // Restore setting values from device browser local storage
      if (localStorage.getItem("mmb_AutoLogin")) {
        $('#AutoLogin').val(localStorage.getItem("mmb_AutoLogin").toLowerCase()).slider('refresh');
       }
    });
  });

I just want to say that, in my experience, I have found a huge amount of conflicting information across the internet regarding JQuery Mobile and I think it should not be this way. There should be clearly documented standards for situations such as the above. This would make it easier for everyone to create mobile web apps.

1
Dima Kuzmich On

You can check working example here

My suggestions are:

  1. Use 'on' function instead of 'delegate' $('#maxsettings').on('pageshow', onPageShow);
  2. Store the value of "mmb_AutoLogin" in local variable, so you reduces the amount of times you access local storage var autoLogin = localStorage.getItem("mmb_AutoLogin")
  3. Run your code on $(document).ready