How to make menu items active based on hash

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

tech