Photo by CHUTTERSNAP on Unsplash

Current Page Link Highlighter - Javascript

By Swapnil Sarwe, Published on 12 Nov, 2008

Introduction:

This tutorial will guide you through the process of writing a javascript snippet which will help you in highlighting a hyperlink which directs to the page which you are currently viewing.

We will be using javascript and CSS to achieve this.

This tutorial is aimed at the beginners who are in the process of learning and exploring javascript which included me too.

To follow the tutorial you need to have a knowledge of basic javascript and also have to know a bit or two about DOM functions in javascript.

If DOM is new to you, please atleast learn about two functions viz. getElementById() and getElementsByTagName().

You can learn more about HTML DOM from HTML DOM Section on w3schools

And then check out the HTML DOM example section and go through the example of getElementById() and getElementsByTagName().

Also check out the HTML DOM Location Object and go through its properties.

Limitation

This tutorial is applicable only to the hyperlinks which link to pages on the site and does not work with folders.

For eg: This script will work with this kind of links About Us

But wont work with this kind of links Category

We will try to add that functionality in the near future.

Approach

There are certain steps we will define before starting to do anything. We will sort down the process in simple words and follow them to achieve our goal.

  1. We will identify the url of the current page which is being viewed and then get the filename of the page from the url. For eg: The url of the current page being viewed is http://blog.swapnilsarwe.com/why-the-hell.html then the filename would be why-the-hell.html
  2. We will then identify the set of links in the menu, with the id of their parent element.
  3. We will check the set of links one at a time, by getting the page name of the url where the links directs us to and then compare that page with the pagename found in 1.
  4. If we find it we will apply a CSS class to the link, which has special properties.

Example:

We will take the following as an HTML code as an example. You can check out the live demo over here. and can get the source code with example in zip format from here.

<div id="navbar">
<ul>
	<li><a href="index.html">Home</a></li>
	<li><a href="link1.html">Link 1</a></li>
	<li><a href="link2.html">Link 2</a></li>
	<li><a href="link3.html">Link 3</a></li>
	<li><a href="link4.html">Link 4</a></li>
	<li><a href="link5.html">Link 5</a></li>
</ul>
</div>

Functions used:

getPage() function takes in the url and returns a filename.

getPage: function(url){
	// reads the last 'slash' and takes text after it - as a pagename
	return url.substring(url.lastIndexOf('/') + 1);
}

Step 1: Identifying the page

We can get the url of the page being viewed by reading the pathname property of the Location Object. For eg: If you are viewing the page http://example.com/link1.html then, window.location.pathname will give you the same path 'http://example.com/link1.html' as a string. We pass this url to getPage() and the function will return us back contact_us.html

var url = window.location.pathname;
curr_page = website.getPage(url);

Step 2: Identify the set of links

To get the set of links first we get their parent tag with its id. We can do so by using the function getElementById() And then we will use getElementsByTagName() function to identify all the <a> tags inside the parent tag with given id

// as per our example we are passing id of the parent div which is 'navbar'
var mainnav = document.getElementById('navbar');
// once we got the reference of the parent we can digg into it to find
// all the <a> elements into an array
var main_nav_links = mainnav.getElementsByTagName('a');

Step 3: Check the link

Now we have the current page and also all the links into an array, now we loop through an array.

for (i = 0; i < main_nav_links.length; i++) {
    // reading a href value from the current 'a' tag in the loop
    currHREF = main_nav_links[i].href;
    // getting a pagename from the obtained 'a' tags href
    currHREFPage = getPage(currHREF);
    // checks the obtained pagename from the current a tag with the curr_page
    if (curr_page == currHREFPage) {
		// add a code to apply a css over here and get out of the function,
		// with the return keyword since probability of finding the same
		// link in the menu again is very less
        return;
    }
}

Step 4: Apply a CSS class to the link

We can apply a CSS class to any element by simply assigning a className property

// this will assign a highlight class to the <a> element.
main_nav_links[i].className = 'highlight';

Complete JS Code

We will execute the code only when the complete window is loaded. hence we will make use of window.onload function

var website = {
    // curr_page variable initialized as '',
    // but on the object initialization
    // will take the value of the current pages url pagename
    curr_page: '',
    // initilization function
    init: function(){
        // reads the current page url
        var url = window.location.pathname;
        // assigns a filename of the url to the curr_page variable
        website.curr_page = website.getPage(url);
    },
    // reads the url and returns the name of the page from the url
    getPage: function(url){
        // reads the last 'slash' / and takes text after it as a pagename
        return url.substring(url.lastIndexOf('/') + 1);
    },
    // this function will crosscheck between the menu links and
    // the current page and highlight the link in the menu
    highlightLink: function(navlist, highlight){
        var link_array = new Array();
        // gets an reference of a object with the help of an id,
        // which will help in reading all the links under it.
        var mainnav = document.getElementById(navlist);
        // reading all the the 'a' link tags
        // falling under the object identified by the passed id.
        // we get result as a collection of all 'a' object in an array
        var main_nav_links = mainnav.getElementsByTagName('a');
        // looping through collection of 'a'
        for (i = 0; i < main_nav_links.length; i++) {
            // reading a href value from the current 'a' tag in the loop
            currHREF = main_nav_links[i].href;
            currHREFPage = website.getPage(currHREF);
            // checks the obtained clean pagename with the curr_page
            if (website.curr_page == currHREFPage) {
                // if found apply the class name,
                // which you want to apply to the specific menu item
                main_nav_links[i].className = highlight;
                // exit the function immediately
                // without checking further liks in menu
                // since to get the same link in the menu again
                // has very less probability
                // still exceptions are possible,
                // hence you can comment or remove
                // the return statement below
                // to check for each and every link
                return;
            }
        }
    }
};
// When window is loaded completely.
window.onload = function(){
    // initiate the website object
    website.init();
    // call the disableLink function,
    // param 1: id of the menu on which you want to highlight link
    // param 2: css class name which defines highlight property
    website.highlightLink('navbar', 'highlight');

};

Conclusion:

The code is ready, try it.

This will work for only those pages which has simple link format.

There are lots of new additions can be made:

  • like removing GET arguments from the links.
  • Also we can add the condition where if the page is not found, it is considered to be the index.html or index.php page
  • And with some additional logic we can also check for slash '/' ending links and highlight them too.

Anyways will look forward to add these things soon and share it with you.

© 2021 Tails - Tailwindcss Page Builder

Instagram Twitter GitHub