In jQuery Mobile, lets say I have the following navigation bar:
<div data-role="navbar">
<ul>
<li><a id="item1">Item 1</a></li>
<li><a id="item2">Item 2</a></li>
<li><a id="item3">Item 3</a></li>
</ul>
</div>
I can then just use jQuery to remove an item to make this look like:
<div data-role="navbar">
<ul>
<li><a id="item1">Item 1</a></li>
<li><a id="item3">Item 3</a></li>
</ul>
</div>
However, jQuery Mobile still renders it as if there are three tabs, and in the middle one, there is just nothing there. So instead of it being spaced out with each tab taking 1/2 of the width, each of the two remaining tabs just takes 1/3 of the width.
I looked closer and jQuery Mobile automatically adds a class to the <ul>
element called "ui-grid-b" and if I change that manually to "ui-grid-a" it then looks fine and the two tabs take up the whole width. However, changing those classes manually seems too hackish and I'm guessing there is a better way to do it. Any ideas?
I didn't figure out a great solution, but I at least figured out a less hacky one.
For my problem, I at least know all of the elements I want in my navbars ahead of time, so I can simply construct several sets of navbars and turn them on or off depending on certain situations. Thus, the HTML looks like phil's solution, but the JS for his solution would instead look like:
$('#navbar1').hide();
$('#navbar2').show();
$('#page1').page();
Try this:
<script type="text/javascript">
function addItem() {
// create the navbar element
var li = $("<li></li>");
var a = $("<a></a>");
var navbar = $("#navbar1");
a.attr("id", "item4").text("Item 4");
li.append(a);
// remove the JQM auto-init classes
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");
}
});
// destroy the navbar widget object
navbar.navbar("destroy");
// append the newly created element
li.appendTo($("#page1 ul"));
// re-init the navbar
navbar.navbar();
console.log(navbar.data());
}
</script>
I guess you already know how to remove an element from navbar now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With