I have a responsive menu using Bootstrap. When the menu is collapsed, I want it to display the name of the page, and when it is open, I want it to show "Menu."
Currently, I have named it "Watch the Trailer" (so let's assume that we are on that page). When I click the button, the title changes, but it only works correctly after the first click. Why is this happening?
Is my approach the best way to achieve this? You can view the code on jsfiddle for convenience.
var menu_title = $(".so_menu_name").html();
$(".navbar button").on("click", function () {
var collapsed = $(".navbar button").hasClass("collapsed");
if (!collapsed) {
$(".so_menu_name").html(menu_title);
}
else {
$(".so_menu_name").html("Menu");
}
});
.nav.navbar-nav .nav-item {
float: none;
}
.nav.navbar-nav .nav-item+.nav-item {
margin-left: 0;
}
.nav.navbar-nav .nav-link {
padding: .25rem 0;
}
.nav.os_menu {
border-top: 2px solid rgba(255, 255, 255, .5);
border-bottom: 2px solid rgba(255, 255, 255, .5);
}
<div class="container">
<nav class="navbar navbar-dark bg-inverse">
<span class="so_menu_name">Watch the Trailer</span>
<button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#collapsingNavbar">+</button>
<div class="collapse navbar-toggleable-xs" id="collapsingNavbar">
<ul class="nav navbar-nav os_menu">
<li class="nav-item active">
<a class="nav-link" href="#">Watch the Trailer<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Screening & Events</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Synopsis</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">The Protagonist</a>
</li>
</ul>
</div>
</nav>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>