jQuery mobile $(document).ready equivalent

Fabio B. picture Fabio B. · Apr 11, 2011 · Viewed 46.2k times · Source

in ajax navigation pages, the classic "document ready" form for performing initialization javascript simply doesn't fire.

What's the right way to execute some code in an ajax loaded page?

(I mean, not my ajax... it's the jquery mobile page navigation system which brings me to that page)

Ok, I did suspect something like that... thanks a lot =) But... it still doesn't work, here's my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>mypage</title>

    <link rel="stylesheet" href="jquery.mobile-1.0a4.min.css" />
    <script type="text/javascript" src="jquery-1.5.min.js"></script>
    <script type="text/javascript" src="jquery.mobile-1.0a4.min.js"></script>
    <script type="text/javascript">
        $('div').live('pageshow',function(event, ui){
          alert('ciao');
        });
    </script>

</head>

<body>

    <div data-role="page">

        <div data-role="header" data-position="fixed">
            <h1>Shopping Cart</h1>
        </div>

        <div data-role="content"> asd


        </div>

    </div>

</body>

Do I need to specify the div id?

Answer

Jura Khrapunov picture Jura Khrapunov · Apr 12, 2011

I spent some time on researching the same since JQM docs are not very detailed at this point. Solution below works fine for me:

<script type="text/javascript">
$('div:jqmData(role="page")').live('pagebeforeshow',function(){
    // code to execute on each page change
});
</script>

You have to implement your own checking flow in order to prevent multiple initialization since the code above will run on every page change