Animate Multiple Background Images – CSS & Javascript Version

by Mar 1, 2018Background Hacks2 comments

This post is an extension of the CSS-only way to do this. Unfortunately, the CSS method (as you’ll see) causes a white flicker between the images, the very first time they are loaded into the div. This CSS & Javascript version fixes that white flash.

This tiny bit of CSS and Javascript gives you a really nice looking background fade/slider.

This is the background effect in a CTA module with a violet background overlay

   Copy and paste the following CSS into the Page’s Custom CSS box.
#animated-bg {
  background: url("https://picsum.photos/1200/800?image=953") no-repeat center center;
  background-size: cover;
  transition: background 3s;
  position:relative;
}
#animated-bg:before {
content:"";
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
background-color:violet;
opacity:0.3;
}

  Type or paste animated-bg in the Section’s CSS ID box.

   Paste the following Javascript into a code module somewhere on the page.


<script type="text/javascript">
var bgImageArray = ["953", "1073", "476", "932"],
base = "https://picsum.photos/1200/800?image=",
secs = 4;
bgImageArray.forEach(function(img){
    new Image().src = base + img; 
    // caches images, avoiding white flash between background replacements
});

function backgroundSequence() {
	window.clearTimeout();
	var k = 0;
	for (i = 0; i < bgImageArray.length; i++) {
		setTimeout(function(){ 
			document.getElementById('animated-bg').style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center";
			document.getElementById('animated-bg').style.backgroundSize ="cover";
		if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (secs * 1000))} else { k++; }			
		}, (secs * 1000) * i)	
	}
}
backgroundSequence();
</script>

This will work in rows, columns, and modules too.

See the Pen Cross-Fade Background Images w/ CSS Transitions & JS by Charlie Wedel (@charliewedel) on CodePen.

Done!

Give this page a share, like, or comment if this worked for you! Leave a comment if you have a question or want to share some love 😀

2 Comments

  1. EchoJonn

    Thank you very much for creating this article, it was very helpful for my situation! This fix works well in Google Chrome, but unfortunately it still shows the white flickering in Firefox.

    Reply
  2. Andrea Cianni

    Thanks for the work. I’m going to do it on my site!!

    P.S. Opening your example pen page i still see the white flicker between the images, just the very first time.

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.