Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS How to keep the page highlighted on the nav bar Reply To: How to keep the page highlighted on the nav bar

#245623
Beverleyh
Participant

Googling something like “highlight current page in menu with javascript” will lead you to various solutions.

But, as luck would have it, I wrote a quick script function for a recent project;

function navHighlight(elem, home, active) {
    var url = location.href.split('/'),
        loc = url[url.length -1],
        link = document.querySelectorAll(elem);
    for (var i = 0; i < link.length; i++) {
        var path = link[i].href.split('/'),
            page = path[path.length -1];
        if (page == loc || page == home && loc == '') {
            link[i].parentNode.className += ' ' + active;
            document.body.className += ' ' + page.substr(0, page.lastIndexOf('.'));
            }
        }
    }
navHighlight('.menu a', 'index.php', 'current'); /* menu link selector, home page, highlight class */

This does as Paulie described – it compares the page file name from the URL to any hrefs in the menu, and if they match, it adds a class to the anchor’s parent li.

Additionally, it adds the page name as a class to the body tag.

So, using the example above, if you were viewing the “about-us.php” page in a web browser, the menu li for “About Us” gets a “.current” class, and the body element get a “.about-us” class;

<body class="about-us">
<ul class="menu">
    <li><a href="/index.php">Home</a></li>
    <li class="current"><a href="/about-us.php">About Us</a></li>
    <li><a href="/contact-us.php">Contact Us</a></li>
</ul>

Note that the navHighlight() function takes 3 parameters;
– the CSS selector to the a elements in the menu
– the file name of the home page
– the class you want to give current/active menu items

Pop it above the closing </body> tag.