0

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.

3 Answers 3

1

My solution

$(document).ready(function(){
  var currentPHP = document.location.pathname.replace(/.+\//i, "")
  $("ul.menu li a[href^='"+currentPHP+"']").parent().addClass("current");
});
Sign up to request clarification or add additional context in comments.

Comments

1

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');
});

3 Comments

Considering that the first li always has the current class ... hmm nice.
@Gerard: It removes the current class from all li's and than narrows the selection down to the one that has an a tag with the desired href, which than gets the current class.
I understand. Didn't know about the existence of the has function in jQuery.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.