September 28th, 2010
I’ve seen several tutorials on how to create a rotating page background using jQuery, but to my surprise pretty much all of them had some major flaws. Here is a technique that I was able to implement very easily with 100% W3 validation.
Getting jQuery on your Page
Since we’ll be using jQuery to handle the background image animation, then we need to get jQuery into our page by adding the following code:
Using the Google-hosted jQuery library will make for a faster load time for your page since there’s almost no chance that you’ll be able to serve this code up faster than Google’s servers.
Adding the Cycle plugin
Next, you’ll need to grab the code for the jQuery Cycle plugin which will be handling the actual animation functionality. Download the plugin here:
- jQuery Cycle Lite Plugin (best for our purposes, only for fading images in and out): http://jquery.malsup.com/cycle/lite
- jQuery Cycle Full Plugin (if you’re looking to do more complex image animations): http://jquery.malsup.com/cycle/download.html
The CSS & HTML Behind this Trickery
Basically, the concept here is, rather than using a regular page background and then continuously swapping out the background image attribute, Here’s what we do:
- Set up the area that will encompassed by the background image by creating divs that span as much of the page as we like. In this example we’re working with a fairly small page background area, but you can make the page background as big or as small is necessary.
- We have the Cycle plugin rotate those divs.
- Place the code for the actual page content beneath the code for the background divs.
- Use absolute positioning to pull the main content up so that it overlaps the rotating background divs.
- Use z-index to put the page content on top of the rotating background divs.
The Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
Happy background image rotating!