Reputation: 10390
I have the following navbar:
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to 'Home', welcome_index_path %></li>
<li><%= link_to 'Projects', projects_path %> </li>
<li><%= link_to 'Users', users_path %> </li>
</ul>
</div>
</nav>
And this jquery to change the selected item based on a click, where .selectednav
has background-color: black
:
<script>
$(document).ready(function() {
$("li").click(function(){
$(this).addClass("selectednav");
$(this).siblings().removeClass("selectednav");
});
});
</script>
However, after clicking on a navbar item, the .selectednav
class only applies to the element for a moment before disappearing.
The only way I have found to resolve this, is by removing the following line from the HTML:
<ul class="nav navbar-nav navbar-right">
But this of course ruins my styling, and I would rather have this here to fit in with the rest of the bootstrap framework.
I have also tried with Bootstrap's built-in active
class, but with the same result (removing the ul
declaration fixes the issue but breaks my style).
Can anyone please tell me what is going on here, or what might be causing this?
It looks like because the page is redirecting to the link after changing the class, the selectednav
class resets to whatever it was originally.
Upvotes: 1
Views: 2761
Reputation: 1
just replace this code just change the class from "selectednav" to "active":
$(document).ready(function() {
$("li").click(function(){
$(this).addClass("active");
$(this).siblings().removeClass("active");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 130
There seems to be no problem with your.
$(this).addClass("selectednav");
$(this).siblings().removeClass("selectednav");
These are working fine with me.
There is another way of accomplishing this task. I have prepared a small fiddle.
Here's a link. Here i am removing the current-item class from all li and then applying it to the current element.
You can take a look and then you will understand it better.
Hope that helps.
Upvotes: 1
Reputation: 21
i think this could help!
<script>
$(document).ready(function() {
$("nav li a").click(function(){
$(this).addClass("selectednav");
$(this).siblings().removeClass("selectednav");
});
});
</script>
Upvotes: 1