Simplest way to make a custom menu with ul li active class When a user clicks on any link, it will be highlighted, providing a smooth experience. In this tutorial, you will learn how to use HTML and CSS to show the active item in an unordered list. Whenever you create a header with multiple list menus, we need to highlight the menu link when the user clicks on it. This allows the user to detect if the menu is clicked or not and see which menu is active. With the help of JavaScript, an event listener is applied which clicks on the current LI and adds the active class to it. This is the way by which you can add the active class to the current element. You can also add CSS to the active class by using the selector ul li a.active.
This is totaly javascript tutorial no jquery involved in this.
Demo
Totaly made with javascript easy to use , To impliment Please follow the below code :
HTML FILE
<div class="main-ul-li-active">
<header>
<nav>
<ul>
<li class="active"><a href="javascript:void(0)">Home</a></li>
<li><a href="javascript:void(0)">About</a></li>
<li><a href="javascript:void(0)">Work</a></li>
<li><a href="javascript:void(0)">Gallery</a></li>
<li><a href="javascript:void(0)">Contact</a></li>
</ul>
</nav>
</header>
</div>
JAVASCRIPT
const classes = {
activeClass :"active"
}
const mainContainer = document
.querySelector(".main-ul-li-active");
const mainHeader = mainContainer.querySelector("header");
const lists = mainHeader.querySelector("ul");
const listItems = lists.querySelectorAll("li");
listItems.forEach(ele => {
ele.addEventListener("click", function() {
lists.querySelector(".active")
.classList.remove(classes.activeClass);
ele.classList.add(classes.activeClass);
})
})
CSS
.main-ul-li-active {
height: 800px;
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-around;
background: #ffc000;
}
.main-ul-li-active header{
display: flex;
width: 100%;
align-items: center;
justify-content: center;
flex-direction: row;
background: #ffffff;
align-self: center;
}
.main-ul-li-active header nav,
.main-ul-li-active header ul
{
width: 100%;
display: flex;
flex-direction: row;
gap: 0px;
list-style: none;
padding: 0;
margin: 0;
align-items: center;
justify-content: center;
}
.main-ul-li-active header ul li {
display: flex;
}
.main-ul-li-active header ul li a {
text-decoration: none;
font-size: 18px;
font-family: Arial, Helvetica, sans-serif;
cursor: pointer;
color: #000000;
padding: 20px 30px;
}
.main-ul-li-active header ul li.active a {
background-color: #6997f8;
color: #ffffff;
}