Ben Pearce
Ben Pearce

Reputation: 7094

Programmatically adding nav bar element in jQuery Mobile

I can create a 2 item nav bar in a jQuery mobile page with the following code snippet:

<div id="nav-bar" data-role="navbar">
    <ul id="nav-list">
        <li><a id="link1" href="#">Nav 1</a></li>
        <li><a id="link2" href="#">Nav 2</a></li>
    </ul>
</div>

I am attempting to programatically add a third nav bar element using various versions of the following code:

$("#nav-list").append("<li><a id='newElement' href='link3'>Nav 3</a></li>");
$("#nav-bar").navbar();
//$("#pageName").page();
//$("#pageName").trigger("create");
//$("#nav-list").listview("refresh");

When I execute this I see the "Nav 3" link appear but it does not take on the jQuery mobile formatting of the other links.

Any help would be greatly appreciated.

Upvotes: 0

Views: 2989

Answers (2)

Gajotres
Gajotres

Reputation: 57309

I had lost my mind because of this problem. .navbar() used to work in previous versions, for some reason not any more.

I have made a function whose job is to add a new element and then rebuild navbar. One part of it is taken from someone else so I cant take full responsibility for this code (mathod used for style stripping).

Here's working example: http://jsfiddle.net/Gajotres/V6nHp/

And here's a method used:

var navbarHandler = {
    addNewNavBarElement:function(navBarID, newElementID, newElementText) {
        var navbar = $("#" + navBarID);

        var li = $("<li></li>");        
        var a  = $("<a></a>");
        a.attr("id", newElementID).text(newElementText);
        li.append(a);

        navbar = navbarHandler.clearNavBarStyle(navbar);

        navbar.navbar("destroy");
        li.appendTo($("#" + navBarID + " ul"));
        navbar.navbar();
    },
    clearNavBarStyle:function(navbar){
        navbar.find("*").andSelf().each(function(){
            $(this).removeClass(function(i, cn){
                var matches = cn.match (/ui-[\w\-]+/g) || [];
                return (matches.join (' '));
            });
            if ($(this).attr("class") == "") {
                $(this).removeAttr("class");
            }
        });
        return navbar;   
    }
}

Upvotes: 0

Nirmal Patel
Nirmal Patel

Reputation: 5168

You should append your HTML in a pagebeforecreate handler before JQM's enhancement starts.

Upvotes: 1

Related Questions