onmouseover change image smoothly

I have an image switching with another one when hovering with mouse, it works well, but I want to make it change smoothly.

Here's my code :

<img src="/images/doubleimgindex.png" class="w-100" 
     onmouseover="this.src='/images/doubleimgindex2.png'" 
     onmouseleave="this.src='/images/doubleimgindex.png'" />

I can't use div for this purpose, that's why I'm asking for help, is it possible?

Upvotes: 0

Views: 1513

Answers (1)

theshark
theshark

Reputation: 151

If you want to fade between the images, you need to have two images on top of each other and fadein/out the upper one:

.container {
  position: relative;
}

.upper-image {
  position: absolute;
  top: 0;
  left: 0;
  transition: opacity 1s;
  opacity: 0;
}

.upper-image:hover {
  opacity: 1;
}
<div class="container">
  <img src="https://picsum.photos/id/100/400/300">
  <img src="https://picsum.photos/id/200/400/300" class="upper-image">
</div>

In Action: https://codepen.io/theshark/pen/rNVVeLO

The fading can be done completely in css as seen in the example :)

The upper image is positioned on top of the lower image via position absolute and completely transparent. On hover the image opacity is scaled to 1 and the image fades in.

If you have further questions about the code, please don't hesitate to ask :)

Upvotes: 4

Related Questions