Check out the fiddle. I have a basic Bootstrap 3 responsive nav like so:
<div id="navbar" class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<a id="navbar-toggle" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="navbar-brand" href="#">Title Title Title</a>
<div id="nav-collapse" class="nav-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="#option1">Option 1</a></li>
<li><a href="#option2">Option 2</a></li>
<li><a href="#option3">Option 3</a></li>
</ul>
</div>
</div>
</div>
The nav items link to sections on the page, rather than different pages so I need the dropdown to hide on click.
Whenever I try to toggle the dropdown manually with jQuery, it messes up future functionality of the dropdown toggle button:
$("#navbar li a").click(function(event) {
// check if window is small enough so dropdown is created
$("#navbar-toggle").is(":visible")
$("#nav-collapse").toggle();
});
Is there a better fix for this?
If you wanted to do this without JavaScript you could simply add the data-target and data-toggle to each list item, like so:
<li data-toggle="collapse" data-target=".nav-collapse"><a href="#option1">Option 1</a></li>
<li data-toggle="collapse" data-target=".nav-collapse"><a href="#option2">Option 2</a></li>
<li data-toggle="collapse" data-target=".nav-collapse"><a href="#option3">Option 3</a></li>
For the navbar, this really only works in the mobile view mode when there is a toggle button. Strange things happen when the navbar is exposed (the toggle button isn't showing).
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