Valery Bulash
Valery Bulash

Reputation: 413

Why jQuery page events not fired?

I have the simple html with 2 JQM pages:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Test table</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
    <script>
        $(function(event, ui) {
            console.log('Whole document (+page 1) ready');
        });

        // Unreachable - doesn't matter which event is "on"
        $('#page_test2').on('pagecreate', function(event, ui) {
            console.log('Page 2 create event fired');
        });
    </script>
</head> 
<body>
    <div data-role="page" id="page_test1">
        <div data-role="content">
            <a href="#page_test2" data-role="button">Open next page</a>
        </div>
    </div>
    <div data-role="page" id="page_test2">
        <div data-role="content">
            <a href="#" data-role="button" data-rel="back">Return to first page</a>
            <div id="place">
            </div>
        </div>
    </div>
</body>
</html>

Found that page2 event handler not reached using "on". What's wrong? Here I found many long topics with very unclear answers.

Upvotes: 0

Views: 404

Answers (2)

Jozeidon
Jozeidon

Reputation: 33

Apply the event listener to the document:

$(document).on('pagecreate', '#page_test2', function() {
    //...
});

Upvotes: 2

Schleis
Schleis

Reputation: 43690

When you are registering the event, the #page_test2 div doesn't exist. You need to wrap the event registration in a $(document).ready() call so that you have all the DOM elements present when you set the event.

Like so:

$(document).ready(function() {
 $('#page_test2').on('pagecreate', function(event, ui) {
            console.log('Page 2 create event fired');
        });
});

You could also move the code to below the declaration of the div's that way they are present in the DOM when the javascript is executed.

Upvotes: 1

Related Questions