Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize pages in jquery mobile? pageinit not firing

What's the right way to initialize objects on a jquery mobile page? The events docs say to use "pageInit()" with no examples of that function, but give examples of binding to the "pageinit" method (note case difference). However, I don't see the event firing at all in this simple test page:

<html>
 <body>  
  <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>  
  <script type="text/javascript" charset="utf-8" src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script>

  <div data-role="page" id="myPage">
    test
  </div>

  <script>
    $("#myPage").live('pageinit',function() {
        alert("This never happens");
    });
  </script>
 </body>
</html>

What am I missing? I should add that if you change pageinit to another event like pagecreate this code works.

---- UPDATE ----

This bug is marked as "closed" in the JQM issue tracker. Apparently opinions differ about whether this is working properly or not.

like image 799
Leopd Avatar asked Sep 25 '11 06:09

Leopd


4 Answers

It started working when I embedded script within page div:

<body>
    <div id="indexPage" data-role="page">
        <script type="text/javascript">
            $("#indexPage").live('pageinit', function() {
                // do something here...
            });
        </script>
    </div>
</body>

Used jQuery Mobile 1.0RC1

like image 136
Wojciech Bańcer Avatar answered Nov 08 '22 02:11

Wojciech Bańcer


.live() is deprecated, suggestion is to use .on() in jQuery 1.7+ :

<script type="text/javascript">
    $(document).on('pageinit', '#indexPage',  function(){
        // code 
    });
</script>

Check the online doc for more information about .on(): http://api.jquery.com/on/

like image 23
geralOE Avatar answered Nov 08 '22 01:11

geralOE


Turns out this is a bug in 1.0b3 that is fixed in the current head. So if you want a fix now, you gotta grab the latest from git. Or wait for the next release.

like image 9
Leopd Avatar answered Nov 08 '22 01:11

Leopd


jQuery(document).live('pageinit',function(event){
    centerHeaderDiv();
    updateOrientation();
    settingsMenu.init();
    menu();
    hideMenuPopupOnBodyClick(); 
})

This is working now. Now all page transitions and all JQM AJAX functionality would work along with your defined javascript functions! Enjoy!

like image 2
Ravindra Padhi Avatar answered Nov 08 '22 02:11

Ravindra Padhi