Reputation: 35
I found this script and I understand why it won't work with my menu as it is but cannot figure out how to get it to work
<script>
$(document).ready(function(){
var i = document.location.href.lastIndexOf("/");
var currentPHP = document.location.href.substr(i+1);
$("ul#menu li a").removeClass('current');
$("ul#menu li a[href^='"+currentPHP+"']").addClass('current');
});
</script>
<nav>
<ul class="menu">
<li class="current"><a href="index.php">Home</a></li>
<li><a href="gallery.php">Gallery</a></li>
<li><a href="location.php">Location</a></li>
<li><a href="about.php">About</a></li>
<li><a href="contact.php">Contact</a></li>
</ul>
Any help would be appreciated. Thanks.
Upvotes: 0
Views: 553
Reputation: 2069
My solution
$(document).ready(function(){
var currentPHP = document.location.pathname.replace(/.+\//i, "")
$("ul.menu li a[href^='"+currentPHP+"']").parent().addClass("current");
});
Upvotes: 1
Reputation: 1635
Looks like you want the class to be on the <li>
not the <a>
elements? You're adding it to the anchors themselves. Try:
$("ul.menu li").removeClass('current');
$("ul.menu li a[href^='"+currentPHP+"']").parent().addClass('current');
(You were also selecting by id not class, as jazZRo pointed out - edited to use class)
Upvotes: 0
Reputation: 1608
You are selecting the ul by it's id: ul#menu
. Select it by the class name: ul.menu
. You are also adding and removing the current class from a and not li. Try this:
$(document).ready(function(){
var i = document.location.href.lastIndexOf("/");
var currentPHP = document.location.href.substr(i+1);
$("ul.menu li")
.removeClass('current')
.has("a[href^='"+currentPHP+"']")
.addClass('current');
});
Upvotes: 1