Reputation: 313
I'm dynamically changing the background image of a div with Javascript.
When the image appears in the div, I want a grey-scale to color transition to happen. But it only happens the first time, if I change the image again the effect does not work.
How do I go about triggering the CSS3 animation when the background url changes ?
I'm steering clear of Jquery on this one, vanilla js only please
.slide {
width: 100%;
height: 100%;
position: fixed;
animation: filter-animation 8s;
-webkit-animation: filter-animation 8s;
}
--
@keyframes filter-animation {
0% {
filter: grayscale(100%);
transition: all 8s ease;
100% {
filter: grayscale(0%);
}
}
}
JS render code:
function renderCurrentSlide() {
document.getElementById('slide').style.background = "url('" + Image.image_data + "') no-repeat top center fixed";
document.getElementById('image-title').innerHTML = Image.title;
document.getElementById('image-caption').innerHTML = Image.desc;
}
HTML:
<div id="slider-container">
<div class="slider-main">
<div id="gallery">
<ul class="images">
<li class="slide" id="slide"></li>
</ul>
</div>
<div class="caption-and-title-holder">
<div id="image-title"></div>
<div id="image-caption"></div>
</div>
</div>
</div>
Upvotes: 1
Views: 1698
Reputation: 196002
You should create a class that only handles the animation and then
var images = [
'http://dummyimage.com/500x500/ff000/ffffff?text=1',
'http://dummyimage.com/500x500/00ff00/ffffff?text=2'
]
function renderCurrentSlide() {
var slide = document.getElementById('slide');
slide.classList.remove('filter-animation');
slide.style.background = "url('" + images[0] + "') no-repeat top center fixed";
void slide.offsetWidth;
slide.classList.add('filter-animation');
}
//for demo only
renderCurrentSlide();
images.shift();
setTimeout(renderCurrentSlide, 10000);
.slide {
width: 100%;
height: 100%;
position: fixed;
filter: grayscale(100%);
}
.filter-animation {
animation: filter-animation 8s forwards;
-webkit-animation: filter-animation 8s forwards;
}
@keyframes filter-animation {
0% {
filter: grayscale(100%);
}
100% {
filter: grayscale(0%);
}
}
<div id="slider-container">
<div class="slider-main">
<div id="gallery">
<ul class="images">
<li class="slide" id="slide"></li>
</ul>
</div>
<div class="caption-and-title-holder">
<div id="image-title"></div>
<div id="image-caption"></div>
</div>
</div>
</div>
credit: https://css-tricks.com/restart-css-animation/
Upvotes: 3