How to make menu items active based on hash

I’m creating a WordPress portfolio site using the Simone theme. I have three menu items that link to the same page but with different hashes:

tovly.com/work/#work-all-work

tovly.com/work/#work-photos

tovly.com/work/#work-videos

The problem is all three menu items are set as active no matter what hash is in the url. At all three of the above urls, the navigation menu looks like this:

What I want is for the navigation bar at tovly.com/work/#work-all-work to look like this:

enter image description here

I also want the same effect at tovly.com/work/#work-photos and tovly.com/work/#work-videos.

How can I do this?

2 Answers
2

This can be accomplised fairly easy by checking the URL then setting the appropriate link to active.

That can be accomplished by the following…

var hash = window.location.hash.substr(1);  // Get the text after the hash
$('a[href="#' + hash + '"]').addClass('active'); // Set the correct link to active

However, there are some things to consider. Someone can access this page from a link that already has a hash, so are code needs to run on page load. Also, the hash can change from within the page so we need to check everytime a link with a # is clicked.

Here is my working/tested example…

$(document).ready(function () {

    function setActive() {
        setTimeout(function () {
            var hash = window.location.hash.substr(1);

            if (hash) {
                $('a[href*="#"]').removeClass('active');
                $('a[href="#' + hash + '"]').addClass('active');
            }
        }, 15);
    }

    setActive(); // On Page Load

    $('a[href*="#"]').click(function () { // On link click
        setActive();
    });

});

Note: the setTimeout is used because there is a slight delay from when a link is clicked and the actual URL is updated

Note 2: This will set and unset an active class directly on the anchor. You may want to set the class on a parent element, like a li or div. You can do that by adding .parent() after the add and remove class selectors.

For example…

$('a[href*="#"]').parent().removeClass('active');
$('a[href="#' + hash + '"]').parent().addClass('active');

Leave a Comment