jQM - Dynamic navbar demo
by Dragan Gaić
HTML
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width"/>
<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>
<div data-role="page" id="index">
<div data-role="header" data-id="foo1" >
<h1>First page</h1>
<a data-role="button" data-theme="a" href="#second" class="ui-btn-right">Next</a>
</div>
<div data-role="content">
<a href="#" data-role="button" id="test-button">Add new navbar element</a>
</div>
<div data-role="footer" data-id="foo1" data-position="fixed">
<div data-role="navbar" id="navbar-test">
<ul>
<li><a href="#">Page One</a></li>
<li><a href="#">Page Two</a></li>
<li><a href="#">Page Three</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>
JavaScript
$(document).on('pagebeforeshow','#index',function(e,data){
$(document).on('click','#test-button',function(e,data){
navbarHandler.addNewNavBarElement('navbar-test','el4','Page Four');
});
});
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;
}
}