0

How can i change image source on hover with only CSS

i tried but was able to find only answers with javascript.

this is my code:

<img src="">

i want to change image to 1.gif when user mouse hover it.

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
Shani
  • 3
  • 1

1 Answers1

0

you can target the image first. and then from there when user mouser over the image you can change src attribute

  1. target image.
const img = document.getElementById('imgId');
  1. make mouser over event like this
img.addEventListener('mouserover', callback);
  1. then you make your own function like this
function callback(event) {
    if (img.src=== '1.gif') {
       img.src = '2.gif';
    }
}
  1. return the 1.gif image when the mouseout
img.addEventListener("mouseout", anotherCallback);

function anotherCallback(event) {
    if (img.src !== "1.gif") {
        img.src = '1.gif';
    } 
}