How to toggle classes in a list item one by one using the mouseover event in JavaScript?
const items = document.querySelectorAll("ul li");
let currentItem;
for (const item of items) {
item.addEventListener("mouseover", e => {
currentItem && currentItem.classList.remove("active");
currentItem = e.target;
e.target.classList.add("active");
});
}
*{
padding:0;
margin:0;
}
.container{
height:100vh;
display:flex;
justify-content:center;
align-items:center;
background-color:#eee;
}
.card{
height:400px;
width:330px;
background-color:#fff;
border-radius:10px;
box-shadow:0px 15px 30px rgba(0,0,0,0.1);
overflow:hidden;
}
.card ul{
list-style:none;
position:relative;
cursor:pointer;
}
.card ul li{
position:absolute;
width:320px;
height:300px;
display:flex;
align-items:center;
justify-content:center;
display:none;
}
.card ul li.active{
display:block !important;
}
.card ul li img{
height:100%;
width:100%;
object-fit:cover;
}
<div class="container">
<div class="card">
<ul id="list-row">
<li class="active"><img src="https://i.imgur.com/dzyiJS2.jpg"></li>
<li><img src="https://i.imgur.com/7BwBYPB.jpg"></li>
<li><img src="https://i.imgur.com/HjkIPFZ.jpg"></li>
</ul>
</div>
</div>
The objective is to cycle through images in the list and add an "active" class to the corresponding list item on hover. The image should change after a 2-3 second interval, similar to a carousel.