Change the class of each item in a list individually by hovering over them with the mouse using JavaScript

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.

Answer №1

//array containing paths of images
const imageArray = ['./imglocation1', 'imglocation2', 'imglocation3', ...]
const imageContainer = document.getElementById("imageCont");

//trigger changeImg() function on hover
imageContainer.addEventListener("mouseenter", function(event) {
  changeImg()
}, false);

function changeImg() {

  //set the first path in the array
  imageContainer.src = imageArray[0];

  //wait for 3 seconds to change image (3000 milliseconds = 3 seconds)
  setTimeout(() => {
    //set the second path in the array
    imageContainer.src = imageArray[1];
    //wait another 3 seconds
    setTimeout(() => {
      //set the third path in the array
      imageContainer.src = imageArray[2];
      //loop through changing images again
      changeImg()
    }, 3000)
  }, 3000)

}
#imageCont {
  position: absolute;
  top: 0%;
  width: 100%;
  height: 35%;
}
<img id="imageCont" src="" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the technique for determining the XPath location of an element through Javascript

Imagine you have a lengthy HTML file filled with various tags, much like the layout of Stack Overflow. If you were to click on a specific element on the page, what would the Javascript function look like to determine the simplest XPath that points to that ...

Error: Unexpected character 'o' encountered in AngularJS syntax

Whenever I try to call this controller, it gives me an error. hiren.controller('hirenz' , function($scope , $http , $location , $routeParams){ $http.post((rootURL + "music") , {'alpha' : $routeParams.alpha , 'name' : $rou ...

PHP and Bootstrap combine in this dynamic carousel featuring thumbnail navigation

Looking to create a dynamic bootstrap carousel with image thumbnails at the bottom? After exploring various code snippets and solutions, I stumbled upon this link. While the code worked, I found the thumbnails to be too small. Below are the functions I use ...

"Extending Material-UI: Utilizing Multiple Snackbar Components

I've been struggling to display multiple warnings using Snackbar from the Material UI library in my React project. I haven't found any examples with React, only Vue. Can anyone help me with this? Here is the code that I have tried so far: https: ...

Angular 5 combined with Electron to create a dynamic user interface with a generated Table

I am working on an Angular Pipe: import {Pipe, PipeTransform} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; import * as Remarkable from 'remarkable'; import * as toc from 'markdown-toc&a ...

In jQuery, a dropdown selection can be filled with multiple textboxes sharing the same class

I'm experimenting with the idea of using multiple textboxes with the same class filled with different dropdown options that also have the same class. However, I am encountering some issues. When I click on a dropdown option, it changes the value in a ...

Verifying Angular JS Routing: Ensuring the Current URL Matches the Route, including Dynamic URL Parameters

Just setting this up: app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/asd/:id/:slug',{ templateUrl:'views/home/index.html', controller:'Home', publicAccess:true, se ...

Arranging Bootstrap 4 columns in a vertical stack

My HTML code is as follows: <html> <head> <title>Title</title> <meta charset="utf-8"> <meta name="description" content="description"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <li ...

Shuffle the elements within each container in the DOM

Currently, I am focusing on designing a card-based layout where each card contains details about the product. One important detail is the phone number, which is displayed in the format 555-555-5555. My current goal is to clear the text value of the phone ...

Navigating with AngularJS through link redirection using anchor tags

How can I achieve smooth scrolling to a specific section using angularJS when clicking on a link? When clicking on a link like this: The page instantly redirects to the specified footer section. I want to implement an angular controller to handle this fun ...

Tips for showcasing an image prior to uploading within a personalized design input file

I am facing an issue with displaying multiple images inside custom style input file labels before uploading them to the database. Currently, the script I am using only displays one image at a time and in random positions. My goal is to have each image ap ...

AngularJS ui-select not responding correctly to selected items

Currently, I am utilizing the ui-select module within AngularJS. <ui-select ng-model="tipData.category" search-enabled="false" name="category" required="required" class="orange-site-color-select custom-select"> <ui-select-match><span clas ...

Issue with Angular $compile directive failing to update DOM element

I'm currently working on a project that involves integrating AngularJS and D3 to create an application where users can draw, drag, and resize shapes. I've been trying to use angular binding to update the attributes and avoid manual DOM updates, b ...

Issue with facebook button in reactJS where onClick() event is not being triggered

I'm facing an issue where my onClick handler is not working with the Facebook button from https://developers.facebook.com/docs/facebook-login/web/login-button/. However, it works fine with a regular div element. Any thoughts on why the onClick event ...

Encountering Internal Server Error when running Node-Express app on render.com with query parameters live

Currently, I am facing an issue while attempting to execute a live route with query using my nodejs express application on render.com. Strangely, all other routes connected to the crud operations are functioning properly except for the search filter route ...

"Error encountered when attempting to upload directory due to file size

Utilizing the webkit directory to upload a folder on the server has been successful, however, an issue arises when there are more than 20 files in the folder. In this scenario, only the first 20 files get uploaded. The PHP code used for uploading the fold ...

Having difficulty using replaceWith to replace text in jQuery

My favorite script successfully adds data to SQL and replaces HTML tags. I have included a text like Add Favorite and used replaceWith to display Remove Favorite. However, the output is not as expected, as shown in the image below. https://i.sstatic.net/x ...

When utilizing the React API Fetch, there may be instances where not all data is returned. However

Having some trouble with my FetchData class. I am receiving a list of data, but it's in an array format. When I try to access specific values like countries: data.Countries[0], I can get individual values based on the index. However, what I really wan ...

Fixing the issue of a div exceeding the height of its parent div in Tailwindcss

One issue I'm encountering is with my card element, which has a fixed height of h-80 in Tailwind. Typically, I use this card within a grid. However, I recently added a div inside the card that is larger than its parent div, and I want it to scroll ve ...

Steps for designing a footer with a fixed width and transparent center gap that stays in place

Looking to create a fixed footer with a transparent gap at the center that is 100% fixed width? No scripts needed! EXPAND THIS WAY <<< ______ FIXED WIDTH GAP ______ >>> EXPAND THIS WAY MY OWN SOLUTION HTML <div id="Ftr"> ...