Fade Between Two Backgrounds

This bit of code fades between two different background images. It's quick, easy, and does good job. The animation is smooth, and you can easily change the speed. Here's an example.

We're using jQuery and TweenMax, so the first thing we'll do is load them up using the free CDN versions that are available:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/TweenMax.min.js"></script>

Next, we load the JavaScript that actually does the background swapping:

$(window).load(function() { /* after everything has loaded, this will start */
	var fade_speed = 1.5; /* in seconds (you can edit this) */
	var pause_length = 2; /* time each image is shown, in seconds (you can edit this) */

	var bgdiv2 = $('#background2');
	var tl = new TimelineMax({repeat:-1});
	var tlint = '+=' + pause_length;
	tl.to(bgdiv2, fade_speed, {opacity:1}, tlint); /* fade the 2nd background in */
	tl.to(bgdiv2, fade_speed, {opacity:0}, tlint); /* and then fade it back out again */

There are comments in the script explaining specific points but, in a nutshell, what's going on is that we stack background #2 on top of background #1 and then fade background #2 in and out by adjusting its opacity. This gives us a nice fade effect, something we couldn't get if we were trying to go from one image to the other within the same element.

To make that work, we'll need a bit of CSS, of course. Include this within your <head> tag (or, without the HTML tags, in your stylesheet):

<style type="text/css">
#background, #background2 {
#background {
	background-image:url('mi.jpg'); /* the image displayed on page load */
#background2 {
	background-image:url('pa.jpg'); /* the image to swap it out with */

The only thing left is to add the divs that will house your two backgrounds. Do that just after the <body> tag:

<div id="background"></div>
<div id="background2"></div>

With those items in place, your backgrounds will start swapping with each other. Pretty easy, right?

Finally, in case you're curious, the photos in the example are ones that I shot this summer in Pennsylvania and Michigan. I scaled the quality way down, just because of server resources. So, that lousy quality is because of that, not anything this animation script is doing.



This post was published on August 14th, 2016 by Robert James Reese in the following categories: CSS, JavaScript, jQuery, and TweenMax Before using any of the code or other content in this post, you must read and agree to our terms of use.