Add Active Class In Navbar ?

The <header> element represents a container for introductory content or a set of navigational links. In <header> we define the <nav> because the <nav> HTML element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes.

The <li> HTML element is used to represent an item in a list. It must be contained in a parent element:

Here we can see the first “li” tag to define an active class, which means the first class is active,

html code

<header>
    <nav id="myDIV">
        <ul class="menu-list">
            <li class="btn active">home</li>
            <li class="btn">page</li>
            <li class="btn">services</li>
            <li class="btn">blog</li>
            <li class="btn">about</li>
            <li class="btn">contact us</li>
        </ul>
    </nav>
</header>

Here, write an active class CSS , style a “menu-list”.

CSS code

header {
       background: gray;
       padding: 15px 30px;
       color: black;
   }
   
   .btn {
       border: none;
       outline: none;
       padding: 10px 16px;
       background-color: #f1f1f1;
       cursor: pointer;
       font-size: 18px;
       margin-right: 15px;
   }
   
   .menu-list {
       list-style: none;
       padding: 0;
   }
   
   .menu-list li {
       list-style: none;
       display: inline-block;
   }
   
   .btn:last-child {
       margin-right: 0px;
   }
   
   .active,
   .btn:hover {
       background-color: #666;
       color: white;
   }

The method getElementById () returns an element with the specified value.

One of the most common methods in the HTML DOM is getElementById ().It is used almost every time you want to read or edit an HTML element.

To create a two-selector

var nav = document.getElementById(“myDIV”);

var btns = header.getElementsByClassName(“btn”);

Then for the loop there, fetch how many buttons are in the nav

When we click on this label, the event will fire and the active class will apply to the selected “menu-list”.

JavaScript

var nav = document.getElementById("myDIV");
     var btns = nav.getElementsByClassName("btn");
     for (var i = 0; i < btns.length; i++) {
         btns[i].addEventListener("click", function() {
             var current = document.getElementsByClassName("active");
             current[0].className = current[0].className.replace(" active", "");
             this.className += " active";
         });
     }

Submit a Comment

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

Subscribe

Select Categories