Highlight link to current page with javascript

If you have a menu on your website and you would like to provide some visual feedback with that one of the links in the menu bar is the page you are on it’s pretty easy with some HTML and CSS.

All you have to do is add a class name to the HTML for that link and then style that class name with CSS.

For example just style the class of “current”:

<li class="current"><a href="http://www.somepage.com">some page</a></li> 

Unfortunately if you are using a common navigation system where you have one file that has all the navigation elements linked to hundreds of pages it’s not possible to change the link style for every link. It defeats the purpose of a common shared file.

Thankfully I found an old blog post by Jonathan Snook that had a script that worked perfectly to strip the link from the current page button. See how “Drama Club” in this screen shot is now light gray and slightly out-dented? It is now an inactive link so if you hover your mouse over it the cursor will not change.

Screen Shot 2015-02-04 at 4.11.16 PM

All you need to make this work is a link to your JS file in your HTML document in the head section like this

<script type=”text/javascriptsrc=”clearlink.js“></script>

Then in the JS file this is the below content is all you need. After that the rest is styling with CSS!

/*
CLCP v2.1 Clear Links to Current Page
Jonathan Snook
This code is offered unto the public domain
http://www.snook.ca/jonathan/
*/

window.onload = clearCurrentLink;

function clearCurrentLink(){
    var a = document.getElementsByTagName("A");
    for(var i=0;i<a.length;i++)
        if(a[i].href == window.location.href.split("#")[0])
            removeNode(a[i]);
}

function removeNode(n){
    if(n.hasChildNodes())
        for(var i=0;i<n.childNodes.length;i++)
            n.parentNode.insertBefore(n.childNodes[i].cloneNode(true),n);
    n.parentNode.removeChild(n);
}

Leave a Reply

Your email address will not be published. Required fields are marked *