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

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

Applying toggle() using css to manipulate various elements at once

Is there a way to toggle multiple divs of varying heights, all with the same class? What is the most effective approach to achieve this? http://jsfiddle.net/hS6RH/41/ $('.smallify').on('click', function() { if ($(this).parent(&apo ...

Can you tell me what this code on Facebook is for?

Upon inspection of Facebook's activity in my browser, I stumbled upon the following code snippet: for (;;);{"t":"refresh"} Attempting to decipher its purpose reveals an infinite loop. Can you identify its function? ...

Is there a way to keep a label in a Material-UI TextField from getting obscured by an adornment when the input is not in focus?

Here is the code for my custom TextField component: <TextField fullWidth: true, classes, helperText: errorText, FormHelperTextProps: getInputProps({ error }), InputProps: getInputProps({ error, endAdornment: error ? <Warning ...

"Exploring the Power of Angular with HTML Checkboxes

I am trying to display a checkbox as either checked or unchecked based on the value of a variable {{CurrentItem.STATUS}}, which can be either 1 or 0. Is there an Angular solution that does not require any javascript/typescript to achieve this? I want the ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

Create a data attribute object and assign to it the prop object received from the parent component

I am struggling with passing an object as a prop from a parent component and then utilizing it to initialize the child component with the received value. The main objective behind this is to create a dialog box that includes a child form component with mu ...

Arranging SVG icons in a row within the navigation bar

Having trouble aligning the icons side by side? Even with margin and padding adjustments, I couldn't get it right. I've scoured multiple sites for a solution but couldn't find one. As an attempt to fix this, I created a bar with aligned butt ...

Having issues with Tailwind classes not being applied properly on dynamically generated pages in Gatsby-node

Currently, I am working on building dynamic pages using gatsby-node. The templates for these pages are stored in the templates/ directory. However, I have run into an issue where I cannot utilize tailwind classes within these templates unless they are al ...

Can values be extracted from a JSON object that is saved in a separate JavaScript file?

In my current project, I am creating unique tables dynamically and displaying them using JavaScript after making an AJAX call. Instead of writing individual code for each table, I'm looking to establish a standard layout where I can customize the desi ...

How to assign a global variable in Angular 2 from within a promise

I have encountered a strange issue while trying to assign a response to a global variable inside an observable. Here's the logic of my program: Fetch the latest playlists IDs from elastic search (using a type definition file for elastic search). T ...

"Utilizing SVG format to manipulate text, adjusting font size within tspan elements

There seems to be an issue with the font size on SVG. Even though both the SVG and paragraph have a font-size of 16px, they appear different. I would like the font size in the SVG to match that of the paragraph. Another concern is how to center <tspan ...

Another class is overriding the border of the text-box

I'm facing a challenge in customizing the material ui css. Specifically, I want to set the border color of a textbox to red. The issue arises when the bottom border gets overwritten. Upon investigation, I discovered that the culprit is the class MuiIn ...

What is the process for incorporating synchronous tasks within an asynchronous function?

const fs = require('fs') const readline = require('readline') const stream = require('stream') const rl = readline.createInterface({ input: fs.createReadStream('logs.txt') }) var uniqueItems = new Set() // ASY ...

Unable to invoke JS function in Drupal 5 file

In my current project using Drupal 5, I have a specific .js file that is included using the code: drupal_add_js(drupal_get_path('module','MTM')."/include/JS_form.js"); Additionally, there is an element on the page: <a onclick="MTM ...

How can I transform the overall value into a percentage in Vue.js or JavaScript?

Is there a way to create a progress bar in VueJS 3 with Nuxt Js by converting the total value to a percentage and displaying it as a style width value? For example, if 40% out of 100% equals 400USD out of 1000USD, can we achieve this using a function in an ...

Resolving Unrecognized Vue Variable in PhpStorm

I'm encountering an issue with my Vue script in PhpStorm. Despite setting the variable redirect_to, I am getting an Unresolved variable syntax error during debugging. Please refer to the image below for further information. How can I resolve this prob ...

Switching an image when hovering over another div - a simple tutorial

Currently, I am in the process of creating a product page for metal address numbers on a website. These numbers are available in four distinct colors: gold, chrome, black, and brown. My goal is to enable users to hover over a specific color div, prompting ...

What is the step-by-step process for chaining ajax requests using $q.deffer?

I have a task that requires the browser to make N requests to the server, where the requests must be synchronous and start only after the previous request has completed. One way to achieve this is by writing a function with a for loop and recursively call ...