1

I'm trying to understand how $.mobile.changePage works. I placed the method $.mobile.changePage in an anonymous function after the last element in the DOM and it didnt work but if I was to place it in document.ready it works fine. How come? any advice much appreciated

<!DOCTYPE html> 
<html> 
<head> 
    <title>My Page</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head> 
<body> 

    <!-- Start of first page -->
    <div data-role="page" id="foo">

        <div data-role="header">
            <h1>Foo</h1>
        </div><!-- /header -->

        <div data-role="content">   
            <p>I'm first in the source order so I'm shown as the page.</p>      
            <p>View internal page called <a href="#bar">bar</a></p> 
        </div><!-- /content -->

        <div data-role="footer">
            <h4>Page Footer</h4>
        </div><!-- /footer -->

    </div><!-- /page -->

    <!-- Start of second page -->
    <div data-role="page" id="bar">

        <div data-role="header">
            <h1>Bar</h1>
        </div><!-- /header -->

        <div data-role="content">   
            <p>I'm the second in the source order so I'm hidden when the page loads. I'm just shown if a link that references my id is beeing clicked.</p>      
            <p><a href="#foo">Back to foo</a></p>   
        </div><!-- /content -->

        <div data-role="footer">
            <h4>Page Footer</h4>
        </div><!-- /footer -->

    </div><!-- /page -->

    <script>
        (function(){ 

                $.mobile.changePage($("#bar"), { transition: "slideup"} );          

        })();// this doesn't work


        $(document).ready(function(){

                $.mobile.changePage($("#bar"), { transition: "slideup"} );

            })//this works

    </script>
manraj82
  • 5,929
  • 24
  • 56
  • 83

1 Answers1

1

document ready dont work correctly with jQuery Mobile. Usually it will trigger before pages are loaded inside the DOM.

If you want to find more about this take a look at this ARTICLE, to be transparent it is my personal blog. Or find it HERE.

To make it work you need to use correct page event, like this:

$(document).on('pagebeforeshow', '#foo', function(){       
    $.mobile.changePage($("#bar"), { transition: "slideup"} );
});

At the same time this is not a good solution. You should not change page while first page is loading, mainly because it will cause jQuery Mobile to misbehave. Ether do it after first page is successfully loaded (page #foo) or change page order and let page #bar be the first page.

Community
  • 1
  • 1
Gajotres
  • 57,309
  • 16
  • 102
  • 130