Add a crossfade while changing img src with javascript

Hi everyone,

I have a JavaScript code to change a src of an img tag on hover. It works but i would like to add some transition to it for a nice visual effect, something like a crossfade. I know that I can do it purely with css but would it be possible to somehow do it with javascript?

I know this is a common technique so I wonder if anyone has ever done it with js.
I’m pasting the code below (in case it helps).

<img src="./assets/images/SwissCheese.jpg" id="monstera"
 onmouseover = "mOver(this)" onmouseout="mOut(this)"> 
function mOver(plant) {
    const plantName = plant.getAttribute('id');
    plant.setAttribute("src", plantsImgSrc[plantName][1]);
    
}

function mOut(plant) {
    const plantName = plant.getAttribute('id');
    plant.setAttribute("src", plantsImgSrc[plantName][0]);
}

Thank you!

In order to fade one in while the other fades out, you’ll need either two images or two places for images. One reduces opacity as the other increases.

Might be two images, or in this case, in wondering if one could be the src, and the other maybe a background image.

1 Like

Thank you. I finally made it work delaying the src change with setTimeout() and changing the image opacity.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.