Ryan Mcguinn
Ryan Mcguinn

Reputation: 825

How to add transition when changing img src on hover?

So I'm trying to add a different image when the original image is hovered over using javascript. The syntax I have is similar to this, which works great.

function imgHover() {
    projectImage.src = '../img/img1.png';
}
function imgHover2() {
    projectImage.src = '../img/img2.png';
}

projectImage.addEventListener('mouseover', imgHover); 
projectImage.addEventListener('mouseleave', imgHover2); 

Now I'm trying to find a way to make the image transition from one to the other (most likely using opacity.) Any suggestions on how to do this? I can't figure it out.

Upvotes: 6

Views: 13115

Answers (1)

emilchristensen
emilchristensen

Reputation: 286

You can't create a transition effect changing just the src tag of an image.

One way of doing this is to create two image that is positioned absolute on top of each other with the top one having an opacity of 0.

If you need to change the hover image dynamically, you can still do that through javascript.

.image-wrapper {
  position: relative;
}
.image-hover {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: opacity 1s ease-out;
}
.image-hover:hover {
  opacity: 1;
}
<div class="image-wrapper">
  <img src="http://via.placeholder.com/350x150?text=normal" class="image" alt="normal" />
  <img src="http://via.placeholder.com/350x150?text=hover" class="image-hover" alt="hover" />
</div>

Upvotes: 10

Related Questions