Carlos Daniel
Carlos Daniel

Reputation: 449

How to add a transition effect to an image when changing its SRC with Javascript?

I want to add a transition effect to an image tag when changing its SRC. I have the following:

let bverse = document.getElementById('bible-verse');

setTimeout(function(){
    bverse.src="../images/bverses/verse2.jpg";
}, 5000);

I have managed to add a transition effect to the background image with:

JavaScript:

let slider = document.getElementById('hero-slider');

setTimeout(function(){
    slider.style.backgroundImage="url(../images/hero/slider-2.jpg)";
}, 5000);

CSS:

.hero-bg {
    background-image: url(../images/hero/slider-0.jpg);
    transition: background-image 2s;
}

But I dont' seem to get the same effect when adding the same styles to the CSS of the bible-verse class. How can I add a transition effect to the bible-verse img tag, without the need of a div container?

Upvotes: 0

Views: 683

Answers (1)

Terminat
Terminat

Reputation: 1237

Transition property won't work with properties like background-image

Here you have the list oof animatable css properties: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

But you could do some workaround here by animating image with @keyframes animations. It depends on what effect you would like to achieve. But I have one example. If you would like to create an animation of image sliding, you could create two images, one would be hidden under the visible image, and via @keyframes you could just move the first visible behind the container it is in and then delete it, when it is offscreen. It would have to been done with combining JavaScript (to add a class that animates an image, delete image, etc) and CSS (to animate an image).

Upvotes: 1

Related Questions