My goal is to add the fadeIn or fadeOut animation to the function called changePicture(). The issue I came across is that i dont know how to add the animation every time after one number of the array runs. For example: images[0] runs and i want the animation to run right after it because im being left out with the linear gradient color (which is some sort of gray) before another image comes across and it just looks horrible. Any help or hints would be appreciated!
let i = 0;
let images = [];
let slideTime = 3000;
images[0] = 'images/banner-bg.jpg'
images[1] = 'images/banner-bg2.jpg'
images[2] = 'images/banner-bg3.jpg'
images[3] = 'images/banner-bg4.jpg'
images[4] = 'images/banner-bg5.jpg'
function changePicture(){
document.getElementById('banner').style.backgroundImage = "linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)),url(" images[i] ")";
if (i < images.length - 1) {
i ;
} else {
i = 0;
}
setTimeout(changePicture, slideTime);
}
window.onload = changePicture;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can achieve this effect by changing the opacity of the banner element.
let i = 0;
let images = [];
let slideTime = 3000;
let animating = null;
let animationInterval = 100;
let pointer = 1;
images[0] = 'images/banner-bg.jpg'
images[1] = 'images/banner-bg2.jpg'
images[2] = 'images/banner-bg3.jpg'
images[3] = 'images/banner-bg4.jpg'
images[4] = 'images/banner-bg5.jpg'
function fadeout(element, time) {
element.style.opacity = 1 - time / slideTime;
// for fadein effect ->
// element.style.opacity = time / slideTime;
}
function changePicture() {
const banner = document.getElementById('banner');
if (animating) {
clearInterval(animating);
animating = null;
pointer = 1;
banner.style.opacity = 1;
}
banner.style.backgroundImage = "linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)),url(" images[i] ")";
const runAnimation = () => {
fadeout(banner, pointer * animationInterval);
pointer ;
}
animating = setInterval(runAnimation, animationInterval);
if (i < images.length - 1) {
i ;
} else {
i = 0;
}
setTimeout(changePicture, slideTime);
}
window.onload = changePicture;
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Hopefully, this works for you