Reputation: 99
Highlight current Menu Item is not working, why? I think I'm doing everything ok, but it's not working.
Can you give me a little help?
Html:
<section id="menu-container">
<div id="bar"><img src="border.png" /></div>
<nav id="menu">
<ul>
<li id><a href="#">Home</a></li>
<li><a href="page.html1">Home2</a></li>
<li><a href="page.html2">Home3</a></li>
<li><a href="page.html3">Home4</a></li>
<li><a href="page.html4">Home5</a></li>
</ul>
</nav>
</section>
Javascript:
$(function(){
var url = window.location.href;
$("#menu ul li a").each(function() {
if(url == (this.href)) {
$(this).closest("li").addClass("active");
}
});
});
CSS:
.active{
background-color:#0C3;
}
Upvotes: 4
Views: 582
Reputation: 534
var url = window.location.href;
$('#menu a').each(function(k,s) {
if(this == url){
$(this).addClass('active');
}
});
Here is a fiddle for the solution. The second link in the fiddle should be the active link.
Upvotes: 0
Reputation: 5169
Use $(this).attr("href")
to get the href
value from your links, since you are already using JQuery.
Combine that with andrew's suggestion to get the end of the current url and you now have better values to test in your if
statement.
$(function(){
var url = window.location.href.split('/');
url = url[url.length-1];
$("#menu a").each(function() {
var $this = $(this); // to minimize DOM traversal
if (url === $this.attr("href")) {
$this.closest("li").addClass("active");
}
});
});
An even better option would be to use advanced JQuery selectors:
$(function(){
var url = window.location.href.split('/');
url = url[url.length-1];
$("#menu a[href='" + url + "'").addClass("active");
});
Upvotes: 1
Reputation: 9583
this.location.href // http://stackoverflow.com/questions/22120946/highlight-current-menu-item-is-not-working-why
try:
var url = window.location.href.split('/');
url = url[url.length-1];
Upvotes: 0