Reputation: 23
Hi i'm working on a off canvas menu and I want to add a class to highlight active menu item but the jquery code I'm currently working with does not seem to add the class to the active link. I tried all potential solutions I came across in the web and nothing seem to work. Any suggestions, ideas, resources?
<nav class="site-menu">
<div class="menu-list">
<ul>
<li><a href="portfolio.php">portfolio</a></li>
<li><a href="projects.php">projects</a></li>
<li><a href="process.php">process</a></li>
<li><a href="blog.php">blog</a></li>
<li><a href="contact.php">contact</a></li>
</ul>
</div>
</nav>
css
.site-menu ul {
list-style: none;
padding: 20px;
margin: 0;
}
.site-menu ul li a {
display: block;
width: 100%;
height: 50px;
line-height: 50px;
color: #7f7f7f;
background: transparent;
text-decoration:none;
}
.menu-list{
position: absolute;
top: 80px;
margin-left: 10px;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
text-transform: uppercase;
letter-spacing: 2px;
text-align: left;
}
.active {
color:#fff;
}
script
var selector = ".site-menu li";
$(selector).click(function(){
$(selector).removeClass('active');
$(this).addClass('active');
});
Upvotes: 0
Views: 2501
Reputation: 5846
When you load a new page the javascript changes will be lost. But you can check what page is active
when the page is loaded like this:
JS
(function($){
$('.site-menu li a').each(function(){
if( $(this).attr('href') == window.location.pathname ) $(this).addClass('active');
})
})
Upvotes: 0
Reputation: 193261
You need to make CSS selector more specific:
.site-menu ul li.active a {
color: #fff;
}
Otherwise the rule .site-menu ul li a
has higher precedence.
Read on the subject: CSS Specificity: Things You Should Know.
Upvotes: 3
Reputation: 53958
You have to change your selector to the following one:
var selector = ".site-menu ul li a";
Upvotes: 0
Reputation: 28328
Try this:
var selector = ".site-menu li";
selector.click(function(){
selector.removeClass('active');
$(this).addClass('active');
});
Upvotes: 1