What methods are available to apply a class to an element in an array when hovering over it?

Is there a way to add a class to an element when hovering over it in an array of elements?

Answer №1

Iterate over each element in the array and attach an event listener for mouseover that applies a specified class.

const elements = document.querySelectorAll('div');
const designatedClass = 'highlight';
elements.forEach(item => item.addEventListener('mouseover', () => {
  item.classList.add(designatedClass);
}))
div {
  height: 100px;
  width: 100px;
  border: 1px solid;
}

.highlight {
  background-color: yellow;
}
<div></div>
<div></div>
<div></div>
<div></div>

Answer №2

If you have multiple elements with different ids or classes, you can try the following approach.

let elements = ['#hud-menu', '#hud-intro', '.hud-shop', '.hud-settings'];

document.querySelectorAll(elements).forEach(item => {
  item.addEventListener('mouseover', () => {
    item.classList.add('blue');
  });
});
div {
  height: 100px;
  width: 100px;
  border: 2px solid;
  border-radius: 10px;
  text-align: center;
}

.blue {
  background-color: blue;
}
<div id="hud-menu">Hud Menu</div><br>
<div id="hud-intro">Hud Intro</div><br>
<div class="hud-shop">Hud Shop</div><br>
<div class="hud-settings">Hud Settings</div>

If you'd like to remove the added class when hovering over an element stops, you can implement the mouseout event as shown in the example below.

let elements = ['#hud-menu', '#hud-intro', '.hud-shop', '.hud-settings'];

// Add class on mouseover
document.querySelectorAll(elements).forEach(item => {
  item.addEventListener('mouseover', () => {
    item.classList.add('blue');
  });
});

// Remove class on mouseout
document.querySelectorAll(elements).forEach(item => {
  item.addEventListener('mouseout', () => {
    item.classList.remove('blue');
  });
});
div {
  height: 100px;
  width: 100px;
  border: 2px solid;
  border-radius: 10px;
  text-align: center;
}

.blue {
  background-color: blue;
}
<div id="hud-menu">Hud Menu</div><br>
<div id="hud-intro">Hud Intro</div><br>
<div class="hud-shop">Hud Shop</div><br>
<div class="hud-settings">Hud Settings</div>

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

Looking to enhance current CSS3 organizational chart by adding a second primary level

I'm having difficulty trying to replicate the first-level (director) box with a vertical line in between. The original chart only has one level with subs below. Take a look at the image provided to see the desired outcome... You can find the CodePen ...

What is the method for displaying map tooltips by default rather than on mouseover?

Currently, I have a script set up to display a map with two markers. Whenever I hover over one of the markers, a popup tooltip appears with location information. My question is, how can I make the information appear by default without needing to hover ov ...

The feature of option display is not supported on Safari browser

I am facing an issue with the functionality of two dropdown menus. The options in the second dropdown are supposed to be shown based on the selection made in the first dropdown. While this feature works perfectly in Chrome, it seems to be malfunctioning i ...

What is the integration process for jTable and Symfony 2?

After creating a Datagrid using jTable, I have included my JavaScript code in twig: <script type="text/javascript> $(document).ready(function () { jQuery('#grid').jtable({ title: 'Table of products', ...

Enhancing CKEditor: Inserting new elements upon each dialog opening

I am facing a challenge where I need to dynamically add varying numbers of elements to a dialog window each time it is opened. Below is the code I am working with: CKEDITOR.on( 'dialogDefinition', function(ev) { var dialogName = ev.data.name ...

Version 10 of Internet Explorer seems to be overlooking the XMLHttpRequest setting of 'xhr.withCredentials = true'

Encountering an issue with a cross-domain ajax call in IE10 (in IE10 mode, not compatibility). Situation: Two domains involved, http://a and http://b. Cookie set for http://b. Currently on page http://a. Goal is to make a CORS request to http://b using X ...

Tips for determining the time and space complexity of this JavaScript code

Here are two codes utilized by my platform to establish relationships between nodes. code1 : const getNodeRelationship = (node1, node2) => { // if node1 and node2 are the same node if (node1 === node2) return null; // check direct parent ...

Is there a way to efficiently display more than 10 data items at a time using the FlatList component in react-native?

Here is the data I am working with: singlePost?.Comments = [ 0: {id: 82, content: "Parent1", responseTo: null} 1: {id: 83, content: "Child1", responseTo: 82} 2: {id: 84, content: "Parent2", response ...

Tips for seamlessly incorporating React Epub Reader into your next js project

Having some trouble integrating the react epub reader with Next Js. It's working perfectly fine with react js, but I keep encountering an error. Can you help me figure out how to integrate the epub reader with next js? Here is the error This is my ...

When using angular $resource.save for savings, the view is forced to redraw and reflow because of the collection watcher

One of the challenges I'm facing involves loading and storing a model using $resource in AngularJS. This particular model is an aggregate with nested collections, which are displayed in an HTML view using ng-repeat. The structure of the model looks l ...

When an option is selected in one dropdown, a list is dynamically populated in another dropdown. However, the entire column then displays the selected row's options in a table format

https://i.stack.imgur.com/q7tMT.png Upon selecting an option from a dropdown within a table row, I make a call to an API to fetch a list of strings into another dropdown field for that specific row. However, the entire column is being populated with that r ...

When trying to insert glyphicons into a textarea, the result is displaying the actual text instead

When the glyphicon is clicked, I want the entered content to be added dynamically to the textarea. $(document).ready(function(){ //Click Event of glyphicon class $(document).on('click','.glyphicon',function(){ ...

Having trouble with the "next" pagination button not loading cards, even though the numbered buttons are working perfectly

My pagination numbers are functioning correctly, but I'm having trouble with my "next" or "previous" buttons. I am using Bootstrap 5 and jQuery to load cards from an array. The issue seems to be with the currentPage variable in my displayList function ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

I am looking to showcase a series of icons linked together by connecting lines

I have successfully designed the layout and added icons, but I am facing difficulty in creating connecting lines between them. I attempted to utilize CSS borders and pseudo-elements, yet I cannot achieve the desired outcome. If anyone could offer a CSS-ba ...

The div is struggling to contain the image, can anyone assist with this issue?

Greetings all! I am a beginner with CSS and currently working on my website. You can check it out at this link. I am facing an issue where the image on my site is not fitting properly and it keeps repeating. Can anyone guide me on how to fix this using CS ...

What could be causing this Angular controller to throw the error message "Error: Unknown provider: nProvider <- n"?

Check out the jsFiddle code here: <div ng-app=""> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> {{data.message + " world"}} </div> </div> function FirstCtrl($scope) { ...

Executing memory function with JQuery replaceWith() and event handlers

Imagine you have the following HTML code: <button id="click-me" type="button">Click Me!</button> Now, picture this jQuery snippet being executed: var button = $('#click-me'); button.on('click', function() { console.l ...

Using nested AngularJS functions in Firefox for enhanced functionality

Check out this simple fiddle I've created. It should display an alert when you press enter in the textbox. The functionality works in the latest versions of IE and Chrome, but not in Firefox: fiddle Here's the HTML code: <div ng-app="app" ng ...

Retrieve data from HTML Form arrays using JavaScript

I have a situation in my forms where arrays are being sent back in the following format: <input class="checkbox-service" name="services['electricity']" type="checkbox"> <input class="checkbox-service" name="services['water'] ...