Malaiselvan
Malaiselvan

Reputation: 1123

Jquery Mobile change page based on a condition

I have 2 Jquery Mobile pages (Login and Home). When the user first launches the application (phonegap) the system check for a local storage variable ('ses_already_login). If the variable is set then the system should not show the login page instead it should show the home page. If the variable is not set then it should show the login page.

Both login and home page contains a header and footer with some form controls which are loaded dynamically using jQuery.

I am doing something like below and I see a blank grey screen. The condition gets through and could see the alert message after that I goes to a blank screen.

$(document).on("pagebeforeshow","#pg_login",function(){
  if(checkAlreadyLogin()){
    alert('I am inside');
    $.mobile.changePage("#pg_home");
    e.preventDefault();
  }
});

I also aware that changePage is deprecated. So, can someone help me how I can redirect/change to the home page.

Upvotes: 1

Views: 861

Answers (1)

Omar
Omar

Reputation: 31732

Solution 1:

You need to use pagecontainerbeforechange in that case not any other event. Because at this stage, you can alter toPage property to redirect user to any page you want.

That event always fires twice and returns toPage which holds either url (string) or jQuery object of target page. However, on first run it returns a jQuery object twice. When it fires for the first time, you have to make sure that toPage is an object and absUrl is undefined, in addition to your condition.

$(document).on("pagecontainerbeforechange", function(e, data) {
  if(typeof data.toPage == "object" && typeof data.absUrl == "undefined" && !condition) {
    data.toPage = $("#login"); /* change to page with ID "login" */
  }
});

Demo


Solution 2:

Another solution is to listen to mobileinit event to check whether user is logged in or not, and then change the position of target page to make "first" page in DOM.

$(document).on("mobileinit", function (e, data) {
    $.mobile.autoInitializePage = false; /* optional - stop auto-initalization */
    if (!condition) {
        $(function () {
            $("#login").prependTo("body"); /* make "login" page first child of "pagecontainer" (body by default) */
            $.mobile.initializePage(); /* optional - manual initialization */
        });
    }
});

You can delay auto-initialization of the framework if you want, however, jQuery functions .prependTo should be wrapped in $(function() {}); or .ready() because mobileinit fires before jQuery library is ready.

Demo

Upvotes: 1

Related Questions