Search code examples
jqueryjquery-mobilemarkupjquery-mobile-button

Adding jQuery Mobile elements to a page after it loads?


In this jsFiddle example...

http://jsfiddle.net/LFgSr/

... I am trying to add jQuery Mobile-style buttons inside a div after the page has been loaded. The big button that appears on the page when the page loads looks great... but when I try to add another similar-looking button "on the fly" (by clicking "Add another button"), it doesn't get styled as it's supposed to (even though I am 'appending' the correct HTML code for the button via jQuery).

Here is the full code...

<!DOCTYPE html>
<html>

<head>

    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
    <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>

</head>

<body>

    <!-- Mark-up -->

    <input id="addButton" type="button" value="Add Another Button">

    <div style="width: 300px; height: 400px; top: 50px; left: 10px; position: absolute; border: 1px solid black;" >
        <section id="page1" data-role="page">
            <div class="content" data-role="content">
            <a href="#" data-role="button">This is a button!</a>
            </div>
        </section>
    </div>

    <!-- Script -->

    <script>
        $(document).ready(function() {
            $('#addButton').click(function() {
                $('.content').append('<a href="#" data-role="button">This is another button!</a><br />');
            });
        });
    </script>

</body>
</html>

What am I missing here? How do I get jQuery Mobile to recognize dynamic updates to the HTML like that?

Thanks!


Solution

  • Here's a working example: http://jsfiddle.net/Gajotres/2uerX/

    $(document).on('pagebeforeshow', '#index', function(){       
        $('#addButton').click(function() {
            $('.content').append('<a href="#" data-role="button">This is another button!</a><br />');
            $('[data-role="button"]').button();
        });
    });
    

    When you dynamically add a new jQM content, jQM must also enhance new content. And in case of button it is done with a:

    $('[data-role="button"]').button();
    

    To find out more about it take a look at my other answer/article: jQuery Mobile: Markup Enhancement of dynamically added content