Home > Blockchain >  What is the simplest way to make hover effect for multiple divs with the same id with css or javascr
What is the simplest way to make hover effect for multiple divs with the same id with css or javascr

Time:04-24

hover, I want the opacity = "0.3"; no hover, I want the opacity = "1"; and h2 and h3 in each div color goes from white to red.

I've googled everywhere and tried to figure it out, but a noob is a noob. here is what I tried but it works for the first div only. why can't work for the rest?

I know if I use class, I can do it with CSS, but I want to apply more functions for h2 and h3 in each div. for example, when hover on box, h2 and h3 display goes from none to block.or color from white to red.

here is the link the code on pen

here is the code

HTML

<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" onm ouseover="hover()" onm ouseout="nohover()"></div>
  <div id="box" onm ouseover="hover()" onm ouseout="nohover()"></div>
  <div id="box" onm ouseover="hover()" onm ouseout="nohover()"></div>
  <div id="box" onm ouseover="hover()" onm ouseout="nohover()"></div>
 
 
</body>
</html>

CSS

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

js

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

CodePudding user response:

Just use :hover css selector to add the styles

#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>
 

CodePudding user response:

Use class (.box) instead of using id (#box). Multiple Ids is not allowed by web accessibility guidelines.

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

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

CodePudding user response:

Use this in the onmouse* events:

function hover(ev) {
    ev.style.opacity = "0.3";
}
 
function nohover(ev) {
    ev.style.opacity = "1";
}
<div id="box" onm ouseover="hover(this)" onm ouseout="nohover(this)"></div>
  • Related