Reputation: 1611
I'm trying to get my menu to highlight the current selected page from that menu.
My HTML code looks like so:
<div class="menu-container">
<div class="menu-wrapper">
<ul id="menu">
<li class="current"><a href="#">HOME</a></li>
<li><a href="#">ABOUT US</a></li>
<li><a href="#">SERVICES</a></li>
<li><a href="#">CONTACT US</a></li>
<li><a href="#">PHOTOS</a></li>
</ul>
</div>
</div>
Firstly, is this the proper way of doing the highlight the current page in menu
? The plan is for each html page to have the class="current"
manually changed to that respective page.
Secondly, how do I get the format to change? What order does the #menu
, li
and .current
have to appear in? I've tried:
#menu li .current{
background: #f00;
}
But no luck.
Upvotes: 1
Views: 268
Reputation: 430
Use this simple Javascript
function LoadCurrentMenu()
{
var str=location.href.toLowerCase();
$("#menu li a").each(function() {
if (str.indexOf($(this).attr("href").toLowerCase()) > -1) {
$("li.current").removeClass("current");
$(this).parent().addClass("current");
}
});
$("li.current").parents().each(function(){
if ($(this).is("li")){
$(this).addClass("current");
}
});
}
and call this function on body load event like below
<body onload="LoadCurrentMenu();">
</body>
Upvotes: 0
Reputation: 8981
try this
OR used JS
$(document).ready(function (e) {
var page = top.location.toString().split('/');
$('#menu').find('a[href="' + page[page.length - 1].toString() + '"]').closest('li').addClass('current');
});
Upvotes: 0
Reputation: 36965
Remove the space between li
and .current
.
#menu li .current
means "any element of class .current
inside a li
inside #menu
."
#menu li.current
means "li
of class .current
inside #menu
."
And yes, it's OK to add class="current"
to the current menu item on each page.
Upvotes: 2
Reputation: 7025
Remove the space between li
and .current
.
#menu li.current{
background: #f00;
}
When you're targeting an element with a specific class, the class should always come directly after the element. If not, you're targeting any child element of the element that has the specified class.
Upvotes: 1