jQM - Slide transition demo with dynamically added pages

by Dragan Gaić

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Share QR</title>
        <meta name="viewport" content="width=device-width,height=device-height,minimum-scale=1,maximum-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/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
    </head>
    
    <body>
        <article data-role="page" id="article1">
            <div data-role="header" data-theme="b" data-position="fixed" data-id="footer">
                <h1>Articles</h1>
            </div>
            <div data-role="content">
                <p>Article 1</p>
            </div>
            <div data-role="footer" data-theme="b" data-position="fixed" data-id="footer">
                <h1>Footer</h1>    
            </div>
        </article>
        
        <article data-role="page" id="article2">
            <div data-role="content">
                <p>Article 2</p>
            </div>
        </article>
        
        <article data-role="page" id="article3">
            <div data-role="content">
                <p>Article 3</p>
            </div>
        </article>    
    </body>
</html>

JavaScript

$(document).on('pagebeforecreate', '#article2, #article3', function(){ 
    $('<div>').attr({'data-role':'header','data-theme':'b','data-position':'fixed','data-id':'footer'}).append('<h3>Article</h3>').appendTo($(this));
    $('<div>').attr({'data-role':'footer','data-theme':'b','data-position':'fixed','data-id':'footer'}).append('<h3>Article footer</h3>').appendTo($(this));    
});

$(document).off('swipeleft').on('swipeleft', 'article', function(event){    
    if(event.handled !== true) // This will prevent event triggering more then once
    {    
        var nextpage = $.mobile.activePage.next('article[data-role="page"]');
        // swipe using id of next page if exists
        if (nextpage.length > 0) {
            $.mobile.changePage(nextpage, {transition: "slide", reverse: false}, true, true);
        }
        event.handled = true;
    }
    return false;         
});

$(document).off('swiperight').on('swiperight', 'article', function(event){   
    if(event.handled !== true) // This will prevent event triggering more then once
    {      
        var prevpage = $(this).prev('article[data-role="page"]');
        if (prevpage.length > 0) {
            $.mobile.changePage(prevpage, {transition: "slide", reverse: true}, true, true);
        }
        event.handled = true;
    }
    return false;            
});