Reputation: 53
Here is my code but not working... It will remove active class after page refresh.
html code
<div id="navbar" class="navbar-collapse collapse navbar-right">
<ul class="nav navbar-nav">
<li><a href="about-us.php">About us</a>
</li>
<li><a href="portfolio.php">Portfolio</a>
</li>
<li><a href="services.php">Services</a>
</li>
<li><a href="contact-us.php">Contact</a>
</li>
<li><a href="#">Blog</a>
</li>
</ul>
</div>
Javascript Code
$(document).ready(function(){
$('#navbar ul li a').click(function(){
$('li a').removeClass("current");
$(this).addClass("current");
});
});
Upvotes: 0
Views: 4323
Reputation: 7289
Can you confirm if the jquery is loaded in the page?
try adding a console.log("item clicked")
in the click function to see if its running
the same code works for me, i just added this css
.current {
background-color: white;
font:black;
font-size:19px;
}
Here is the fiddle link https://jsfiddle.net/vigneshvdm/0w0rnx4x/
Upvotes: 0
Reputation: 10083
For your current setup, it seems you do not need to use javascript to add classes as these are direct links with no dropdowns, so obviously clicking them will redirect to another page and classes will be removed. A simple solution without JS is like this:
Your css would be like this:
.about-body .about-link,
.portfolio-body .portfolio-link,
.services-body .services-link,
.contact-body .contact-link,
.blog-body .blog-link
{
background-color: red; /* or other styles you have in your active class */
}
<div id="navbar" class="navbar-collapse collapse navbar-right">
<ul class="nav navbar-nav">
<li class="about-link"><a href="about-us.php">About us</a>
</li>
<li class="portfolio-link"><a href="portfolio.php">Portfolio</a>
</li>
<li class="services-link"><a href="services.php">Services</a>
</li>
<li class="contact-link"><a href="contact-us.php">Contact</a>
</li>
<li class="blog-link"><a href="#">Blog</a>
</li>
</ul>
</div>
One thing to note here is that you would need to have the body classes accordingly on every page. e.g. your about-us page should have about-body
class on body
tag. Hope that makes sense.
Upvotes: 0
Reputation: 33218
I create an example using localStorage to set the active element and to keep it active on page load:
$('#navbar ul li a').click(function() {
$('li a').removeClass("currunt");
$(this).addClass("currunt");
localStorage.setItem('active', $(this).parent().index());
});
var ele = localStorage.getItem('active');
$('#navbar ul li:eq(' + ele + ')').find('a').addClass('currunt');
Upvotes: 4