r/learnjavascript • u/IntelligentSteak7709 • May 03 '26
Java script animation
Very new to javascript so please bear with me LOL.
I'm trying to make an image change using SetInterval with a fade in between. How would I add the animation to this code?
const images = ["images/negan_image1.jpg", "images/negan_image2.webp", "images/2 (1).png" , "images/negan_image5.webp"];
let index = 0;
setInterval(() => {
document.getElementById('negan-image').src = images[index];
index = (index + 1) % images.length;
}, 3000);
2
Upvotes
1
u/abrahamguo May 03 '26
Make a separate
imgelement for each image — you can't do the fade effect with only oneimgelement.Use CSS
position: absoluteto position all of the images on top of each otherSet
opacity: 0on all but one image in order to make them invisible.When you are ready to transition from one
imgto another, useindexbefore updating it to know which image to fade out (i.e., setopacityto 0).Use
indexafter updating it to know which image to fade in (i.e., setopacityto 1).Set the CSS
transitionproperty on each of the images in order to make them fade in and out rather than instantly changing their opacity.