Open In App

How To Make Active Navbar In HTML CSS And JavaScript ?

Last Updated : 27 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

An active navbar refers to a navigation bar on a website where the current or active page is visually highlighted or distinguished from the other menu items. In this article, we are going to learn how to make an Active Navbar in HTML, CSS, and JavaScript.

Prerequisites:

Approach

  • Use HTML to give structure using an unordered list (<ul>) and list items (<li>) for each navigation element, assigning unique IDs or classes.
  • Design the navigation bar using CSS and give it a special look when a menu item is selected.
  • In JavaScript, Select all navigation items with the class ‘.nav-item’ using const navItems = document.querySelectorAll('.nav-item');.
  • Iterate through each navigation item using navItems.forEach(item => {...}).
  • Add a click event listener to each navigation item to respond when a user clicks on it.

Example: In this example, we have implemented the above approach.

Javascript




//script.js
document.addEventListener('DOMContentLoaded',
    function () {
        const navItems = document
            .querySelectorAll('.nav-item');
 
        navItems.forEach(item => {
            item.addEventListener('click',
                function () {
                    navItems.forEach(navItem => navItem
                        .classList.remove('active'));
                    this.classList.add('active');
                });
        });
    });


HTML




<!-- Index.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="styles.css">
    <title>Active Navbar</title>
</head>
 
<body>
 
    <nav>
        <ul>
            <li class="nav-item" id="home">
              <a href="#">Home</a>
              </li>
            <li class="nav-item" id="about">
              <a href="#">About</a>
              </li>
            <li class="nav-item" id="services">
              <a href="#">Services</a>
              </li>
            <li class="nav-item" id="contact">
              <a href="#">Contact</a>
              </li>
        </ul>
    </nav>
 
    <img src=
 
    <script src="script.js"></script>
</body>
 
</html>


CSS




/* styles.css */
body {
  margin: 0;
  font-family: Arial, sans-serif;
}
 
img{
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
}
 
nav {
  background-color: #333;
}
 
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
 
.nav-item {
  float: left;
}
 
.nav-item a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
 
.nav-item.active {
  background-color: #4CAF50;
}


Output:

gfg-navbar



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads