Add CSS keyframe animation every image switch
12:52 13 Apr 2020

I have an image tag where in every 3 seconds it changes to a different image and I want to add into it an animation style where every time the image switch, a CSS animation keyframe will take effect. It seems that I cant figure out how to apply the animation in JavaScript. Here's what I've tried so far:

My JavaScript:

let indexObj = {

imageChange: document.getElementById("imageChanger"), //id of the image tag
imagePath: ["images/Ps_Logo.png", "images/Pencil.png"],
indexPos: 0,


ChangeImage: () => {

    setInterval(() => {
        indexObj.imageChange.src = indexObj.imagePath[indexObj.indexPos];
        indexObj.imageChange.classList.add("imageToChange"); // imageToChange is the name of the css class where the animation is written on.
        indexObj.indexPos++;
        if (indexObj.indexPos === 2) {
            indexObj.indexPos = 0;
        }
    }, 3000)
  }
}

        indexObj.ChangeImage();

Here is my CSS code. The class and animation keyframe:

.imageToChange {
height: 55px;
width: 70x;
border-radius: 20%;
animation-name: animateImage;
animation-duration: .5s;
animation-fill-mode: forwards;
}

@keyframes animateImage {
0% {
    margin-top: 2px;
    opacity: 0;
}
50% {
    margin-top: 7;
}
100% {
    opacity: 1;
    margin-top: 9px;
 }
}
javascript html css