Open In App

How To Make Active Navbar In HTML CSS And JavaScript ?

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

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






//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');
                });
        });
    });




<!-- 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>




/* 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:




Article Tags :