Reputation: 5313
If I'm using the below simple JS to change a background image on a timer, can I apply CSS transitions to make these fade in instead of just swapping instantly?
var images = new Array(
'../images/pic1.jpg'
,'../images/pic2.jpg'
,'../images/pic3.jpg'
);
var i = 0;
function swap() {
var elm = document.querySelector('.myCSSClass');
if (i >= images.length) { i = 0 };
elm.style.backgroundImage = 'url(' + images[i] + ')';
i += 1;
}
window.onload = setInterval(swap, 2000);
For instance, I'm trying in CSS:
.myCSSClass{
transition: background-image linear 0.3s;
}
But not getting any result. I feel like this isn't possible because javascript is just overwriting the image?
Upvotes: 1
Views: 306
Reputation: 272909
You simply need to make sure all the images are initially loaded to have the transition or each time you will call a new image you will get an abrupt change because it will be loading Or you have to wait for one cycle because your script will load the images within that cycle.
var images = new Array(
'https://picsum.photos/id/0/300/300',
'https://picsum.photos/id/10/300/300',
'https://picsum.photos/id/15/300/300'
);
var i = 0;
function swap() {
var elm = document.querySelector('.box');
if (i >= images.length) {
i = 0
};
elm.style.backgroundImage = 'url(' + images[i] + ')';
i += 1;
}
window.onload = setInterval(swap, 2000);
.box {
transition: background-image linear 0.5s;
width: 200px;
height: 200px;
background-size: cover;
/* This will force the initial load of all the images*/
background-image:
url(https://picsum.photos/id/0/300/300),
url(https://picsum.photos/id/10/300/300),
url(https://picsum.photos/id/15/300/300);
}
<div class="box"></div>
In the above you will have fading only on some browser like chrome. Here is another idea where I will consider another layer and rely on opacity change:
var images = new Array(
'https://picsum.photos/id/0/300/300',
'https://picsum.photos/id/10/300/300',
'https://picsum.photos/id/15/300/300'
);
var i = 0;
function swap() {
var elm = document.querySelector('.box');
if (i >= images.length) {
i = 0
};
elm.style.backgroundImage = 'url(' + images[i] + ')';
i += 1;
}
window.onload = setInterval(swap, 2000);
.box {
width: 200px;
height: 200px;
background-size: 0 0;
/* This will force the initial load of all the images*/
background-image:
url(https://picsum.photos/id/0/300/300),
url(https://picsum.photos/id/10/300/300),
url(https://picsum.photos/id/15/300/300);
position:relative;
z-index:0;
}
.box:before {
content:"";
position:absolute;
z-index:-1;
top:0;
left:0;
right:0;
bottom:0;
background-image:inherit;
background-size:cover;
animation:op 1s alternate linear infinite 1s;
}
@keyframes op {
to {
opacity:0;
}
}
<div class="box"></div>
Upvotes: 2