DEV Community

Cover image for Styling Active Navigation Links Using Vanilla JS and CSS.
Felix Owino
Felix Owino

Posted on

Styling Active Navigation Links Using Vanilla JS and CSS.

What are navigation links? What does it mean when they are active? Every website you have visited has one or more pages. Websites that have more than one page use navigation links. Navigation links help to connect all the pages on the website for easy access from different locations within the website. A link is active when the user is currently viewing a page related to the link. For example, if you open the home page of a website, the active link is the link named 'Home'.

Why is it important to style active navigation links?

Applying a set of styles on active navigation links helps to improve user experience on your website. Users get a better experience on your website when they can distinguish between active links and inactive ones. An active navigation link helps users of your website to know which location they are currently in on your website. An active link helps users know where they are without having to read the page content. Styling active links differently from inactive links allows users to tell the difference between the two.

What about visited Links?

It is easy to confuse between active links and visited links. Visited links will always stay visited even if you are not currently on that page. One good example is Google search results. Every link you visit on Google will always have a different color even if you are not currently viewing that page. Active links are styled to only have specific styles when you are in that location.

Prerequisites

In order for us to implement styling of active links, you will need to be familiar with the following languages:
- HTML
- CSS
- JavaScript
You do not need to be an expert in any of these languages. As for JavaScript, you need to at least know how to query elements from the DOM and event handling. We will also need a text editor. I will be using VS Code but you can use anyone that you are familiar with.

How does it work?

In this article, we will create three web pages that are linked together with a simple navigation bar consisting of three navigation links. In most cases when we talk of links we use HTML anchor elements. However, in this article, we will use purely buttons. We will use an HTML button element with an inline click event handler in each case to emulate the behavior of an anchor element. Our website will have a home, about, and services pages.

Before we start handling navigation, we will need to write the following pieces of code.

Home page home.html



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Home</title>
</head>
<body>
    <header>
        <button>Home</button>
        <button>About</button>
        <button>Services</button>
    </header>
    <h1>Welcome to our home page</h1>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode

About Page about.html



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>About Us</title>
</head>
<body>
    <header>
        <button>Home</button>
        <button>About</button>
        <button>Services</button>
    </header>
    <h1>About Us</h1>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode

Services page services.html



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Services</title>
</head>
<body>
    <header>
        <button>Home</button>
        <button>About</button>
        <button>Services</button>
    </header>
    <h1>Our Services</h1>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode

Intial styles styles.css



header{
    display: flex;
    flex-direction: row;
    gap: 1rem;
    justify-content: center;
    align-items: start;

}

button{
    border: none;
    color: white;
    background-color: rgb(32, 32, 32);
    padding-inline: 2rem;
    padding-block: 1rem;
}
h1{
    text-align: center;
}


Enter fullscreen mode Exit fullscreen mode

Open home.html in your favorite browser. Your browser view of the work should look like this.

Initial View of home page without active styles

Assigning links to buttons.

In order to use buttons to navigate our page, we use the click event listener. In this article, we assign an event handler code to the onclick attribute. We use the window object of the JavaScript Library to assign URLs to the buttons. We can assign URLs to the buttons as follows.

Apply this change to the headers of all three pages



<header>
        <button
            onclick="window.location.assign('/home.html')"
        >
            Home
        </button>
        <button
            onclick="window.location.assign('/about.html')"
        >
            About
        </button>
        <button
            onclick="window.location.assign('/services.html')"
        >
            Services
        </button>
    </header>


Enter fullscreen mode Exit fullscreen mode

More About window.location.

window is a JavaScript object that can be used within the browser to perform operations on the web page. One of the properties of the window object is the location property. The location property carries the information relating to the current page. location.href returns the URL of the current page. We can see how this works in the browser's console. Open the browser console using Ctrl + Shift + I, type the following code and press enter.



window.location.href


Enter fullscreen mode Exit fullscreen mode

Expected output



'http://127.0.0.1:5500/services.html'


Enter fullscreen mode Exit fullscreen mode

The window.location.href property returns the current URL depending on what page you are currently viewing. The result should be the same as the URL in the browser`s address bar. Yours may be different from mine depending on the page you are on.

Changing URLs using window.location

In the code snippet above, we are using the assign function of the window.location property to change current URL. window.location.assign(url) changes the current page by assigning a new value to window.location.href property. Using the assign function, we can now navigate through the web pages by clicking the buttons.

Styling Currently active link

At this point, we are going to use JavaScript to alter the background color of the navigation buttons based on the current URL. We will do this in the following steps:
1. Use window.location.href to get the value of current
URL
2. Get buttons using queryselectorAll function of the
document object
3. Use the includes function of the String object to check

if the current URL contains the text content of the
button.
4. Change the color of the button if step 3 evaluates the
true

Include 'script.js` on HTML files

Include the script in the head of all html pages as follows



<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="script.js" defer></script>
    <title>About Us</title>
</head>


Enter fullscreen mode Exit fullscreen mode

JS code script.js



const locationHref = window.location.href
const buttons = document.querySelectorAll('button')


buttons.forEach(button => {
    // trim to remove white spaces and convert to lowercase
    const textContent = button.textContent.trim().toLowerCase()
    if(locationHref.includes(textContent)){
        button.style.backgroundColor = 'orangered'
    }
})


Enter fullscreen mode Exit fullscreen mode

Your final work should look like this screenshot.
Final view of services page with active styles

Conclusion

Styling active navigation links is an important practice for a good user experience. You don't want your users to get lost on your page because you forgot to style active links. If you need to read more about window.location, feel free to do so.

Top comments (0)