How can I create a hover effect for multiple divs sharing the same id using CSS or JavaScript in the easiest way possible?

When hovering, I want the opacity to be set at "0.3"; when not hovering, it should be set at "1". Additionally, the color of h2 and h3 in each div should transition from white to red.

I have searched extensively online and tried to solve this issue, but as a beginner, I am struggling to understand. The solution I attempted only works for the first div - why doesn't it work for the others?

I am aware that using classes would allow me to achieve this with CSS alone, but I want to incorporate more functions for h2 and h3 within each div. For example, on hover, h2 and h3 display transitions from none to block, or their color shifts from white to red.

Here is the link to view the code on CodePen: the code on pen

Below is the HTML code:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="box" onmouseover="hover()" onmouseout="nohover()"></div>
  <div id="box" onmouseover="hover()" onmouseout="nohover()"></div>
  <div id="box" onmouseover="hover()" onmouseout="nohover()"></div>
  <div id="box" onmouseover="hover()" onmouseout="nohover()"></div>
 
</body>
</html>

CSS

#box{
    background: blue;
    width:100px;
    height: 100px;
    margin: 20px;
 }

JavaScript

function hover() {
   document.getElementById("box").style.opacity = "0.3";
}
 
function nohover() {
   document.getElementById("box").style.opacity = "1";
}

Answer №1

Utilize the :hover css selector to apply the desired styles upon hovering

#box{
    background: blue;
    width:100px;
    height: 100px;
    margin: 20px;
  }
  
#box:hover {
  opacity: 0.3;
}
  <div id="box" ></div>
  <div id="box" ></div>
  <div id="box" ></div>
  <div id="box" ></div>
 

Answer №2

It is recommended to use the class (.box) instead of id (#box) for web accessibility compliance. Multiple Ids are not allowed.

https://www.w3.org/TR/WCAG20-TECHS/H93.html

.box {
    background: blue;
}
.box:hover {
    background: red
 }

Answer №3

Employ the use of this within the onmouse* events:

function showHoverEffect(ev) {
  ev.style.opacity = "0.3";
}
 
function removeHoverEffect(ev) {
  ev.style.opacity = "1";
}
<div id="box" onmouseover="showHoverEffect(this)" onmouseout="removeHoverEffect(this)"></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

Error message indicating that the function 'slice' is not defined for the data variable

I've already searched for solutions to a similar issue, but none of them worked for me. I'm dealing with an object that fetches a list of cities including their names, populations, and states. Here is my HTTP service request: cidadesUrl = 'h ...

Yii2 HTML helper input must be marked as required

This is the form I have generated using the HTML helper: <div class="row"> <div class='form-group col-lg-6 col-sm-6'> <?= HTML::label('Name:','PropertyContactsNew',['class' => 'control-l ...

Troubleshooting: Issues with Angular form validation functionality

I am completely new to Angular and attempting to create a signup form. Despite following tutorials, the form I've built doesn't seem to be validating properly. Below is the code that I have been using: <div class="signup-cont cont form-conta ...

Changing the Direction of News Ticker Movement from Right to Left

I need to switch the news ticker movement direction from right to left to left to right because I will be using Arabic language, so it is crucial to change the movement direction. Despite trying for several days, I have been unable to find a solution. HTM ...

A more effective method for restricting the properties of a field in an aggregate query

In my MongoDB query, I am attempting to use the aggregate function to fetch data from one collection while limiting the amount of data retrieved from another collection. Here is the code snippet that I have come up with: getFamilyStats: function (req, res ...

Problem with Jquery show/hide feature only resolved after refreshing the page

I built a checkout page that consists of three fieldsets with unique IDs - 1, 2, and 3. I want the page to initially display only fieldset 1 while hiding fieldsets 2 and 3. Here is the jQuery code I used: $(document).ready(function(){ $("#1").show(); ...

Creating a dynamic multi-item carousel with Materialize (CSS) cards using data from a loop - here's how!

Using a for loop, the following code generates a list of cards. These cards are intended to be displayed in a carousel with 4 cards visible at once, and a next arrow button allows users to navigate through the next set of 4 cards. Materialize cards have ...

Techniques for animating background image using jQuery

Hello there! I'm currently experimenting with animating a background image using jQuery. Despite following a tutorial, I haven't been successful in getting my test page to work as intended. The blue Facebook icon displays, but it doesn't ani ...

Ensuring that a header one remains on a single line

Within this div, I have set the width and height to be 250px. Specifically, the h1 element inside the div has a height of 50px. Users who are updating content on my website can input any text they desire within this box. However, when the text within the ...

Adjust CKEditor's height within Vue.js

I recently began experimenting with integrating ckeditor5 into a Vue.js project. However, I encountered an issue where I couldn't manually adjust its height. Below is the code snippet I used - could you please review it and let me know if there are an ...

Including a JavaScript file in an HTML document initiates a server request, which can lead to potential errors

I am currently developing a web application using Express and Node.js on the backend, with EJS as the templating engine on the frontend. Here is a snippet of my app.js file: app.get('/book/:id', (req, res)=>{ var book_id = req.params.id; cons ...

Utilizing ControlValueAccessor in various components

I am currently working on a component that implements the ControlValueAccessor interface, and I am facing some difficulties in understanding how to properly utilize it: // Angular Imports import { Component, OnInit, forwardRef, Output, EventEmitter, OnC ...

Type of flow: customizable prop types for React components that can be extended

In the scenario where a SelectOption component is present, with props defined as: type OptionType = { +id: string, +label: string, } type Props = {| +options: OptionType[], +onItemPress: OptionType => void |} I intentionally left the OptionType ...

Javascript Code for toggling the visibility of a panel

I need help with a JavaScript code that can show or hide a panel depending on the data in a grid. If the grid has data, the panel should be displayed, but if the grid is empty, the panel should be hidden. I attempted to use the following code, but it did ...

Configuring the space beneath a multi-line text with a bottom border distance or shadow

I am looking to add a bottom border with less spacing than default for specific text, creating a look similar to this image: https://i.sstatic.net/sCQii.png Unfortunately, it seems the border property cannot achieve this effect. I am experimenting with t ...

Tips on defining the specific CSS and JavaScript code to include in your Flask application

I am currently working on a web application using Flask and I need to specify which CSS and JS files should be included in the rendered HTML page based on a condition. There are times when I want to include mycss1.css and myjs1.js: <link href="/sta ...

Error encountered in React: Unable to access property of splice as it is undefined

As I am still getting acquainted with React/JS, I am currently navigating through the process of developing a mobile website. My main goal is to incorporate a delete function without the use of a button. My approach involves utilizing a long-press event, a ...

Tips for maximizing the potential of the HTML5 <nav> element

While creating a theme with multiple menus in the header, I'm pondering whether to use separate nav tags for each menu or wrap them all inside one nav tag? You can see an example on codepen. header-a wraps everything inside a single nav tag. header ...

Choose all the HTML content that falls within two specific tags

Similar Question: jquery - How to select all content between two tags Let's say there is a sample HTML code as follows: <div> <span> <a>Link</a> </span> <p id="start">Foo</p> <!-- lots of random HTML ...

No visuals render with Three.js

I am experimenting with three.js for the first time and I am having trouble understanding why I can't see the color on my torus. I've tried setting alpha to true in my render. I attempted to change the camera position in the z-axis. I also tri ...