Home > Back-end >  adding mouseover event to img element doesn't work
adding mouseover event to img element doesn't work

Time:06-15

this is my html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link href="style.css" rel="stylesheet" type="text/css" />
    <script src="script.js"></script>
  </head>
  <body onl oad="load();">
    <img src="img1.png">
    <img src="img2.png">
    <img  src="img3.png">
  </body>
</html>

And I want the 3rd image to go to the left when mouse is over it. (It has position: absolute; on it) using this js code

let img;
function load(){
  img = document.querySelector(".img3");
  img.addEventListener("mouseover", mouseover);
}
function mouseover(){
  img.style.left = "0px";
}

but mouseover never gets called. (Checked with logging)

CodePudding user response:

you can use the hover method in css to achieve this, it would look something like:

.img3:hover {
  width: *put desired width here*;
  height: *put desired height here*;
}

You might need to use id tags to make the default image shrink when the img3:hover event occurs. You can find more information about it here: https://developer.mozilla.org/en-US/docs/Web/CSS/:hover

CodePudding user response:

In your css you can use

.img3:hover{
  /* css here */
}

If you use this method you do not need to use Javascript to change css on hover it is built in to css already :)

  • Related