1

I am using this code to change from one image to another:

<img title="Hello" src="selfie.jpg" onmouseover="this.src='hero_image.png'" onmouseout="this.src='selfie.jpg'" />

I need help with the code so I can slow the transition from one image to the next.

Tyler Durden
  • 860
  • 6
  • 17
  • Please provide mode details like code snippet or codepen so someone can answer to your question – Parth Patel Dec 24 '21 at 14:05
  • Please refer [How to ask a good question](https://stackoverflow.com/help/how-to-ask) and add a [Minimum Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Tyler Durden Dec 24 '21 at 14:10
  • As soon as an image loads it paints, no transitions can be made on that. I recommend you to keep both loaded inside a box, to listen the box event and then transition from one image to other with `opacity`, `transform` or whatever effect you want to achieve. – Leo Dec 24 '21 at 14:21
  • So with my current code, is there no way to to slow down the transition from one image to another? – rachelmc881 Dec 24 '21 at 14:34
  • Does this answer your question? [how do I add an animation to my onmouseover javascript function(changing image on hover)?](https://stackoverflow.com/questions/60951714/how-do-i-add-an-animation-to-my-onmouseover-javascript-functionchanging-image-o) – Nikita Skrebets Jan 03 '22 at 02:46

1 Answers1

1

The ideal solution to this would be rendering the two images and changing their opacity instead of changing src for the same tag. Something like :

<div id="container">
  <img class="bottom" src="hero_image.png" />
  <img class="top" src="selfie.svg" />
</div>

Once you are playing with the opacity, the transition effect can be applied using the following CSS :

#container img {
  position:absolute;
  left:0;
  transition: opacity 1s ease-in-out;
}

#container img.top:hover {
  opacity:0;
}
Tyler Durden
  • 860
  • 6
  • 17