Random full page background

This Tutorial is written with Drupal 7 in mind. However, it can be applied to any website.

While upgrading and redesigning thebga.org golf association website, I decided to figure out how to have a random full page background part of the design. Drupal 7 makes it easy to include js and keep it, the theme and templates all separate from the Drupal core. The key is separation of your theme and it’s modules from the Drupal core and it’s modules. The Zen theme and Starter Kit make this very easy to accomplish.

Create or add this code to a javascript file in your themes “js” folder. I saved the file as random-bg.js (/sites/all/themes/thebga/js/random-bg.js).

(function ($) {
    $(document).ready(function() {
	var bgimages = [
	    'ovl_2010_wellman_rw.jpg',
	    'ovl_2010_wellman_sunday_am.jpg',
	    'ovl_2010_wellman_tobaccoroad_01.jpg',
	    'ovl_2010_wellman_tobaccoroad_14.jpg',
	    'ovl_2011_bridges_15.jpg',
	    'ovl_2011_dos-equis_sunday.jpg',
	    'ovl_2011_spam_friday01.jpg',
	    'ovl_2011_spam_friday02.jpg',
	    'ovl_2011_spam_friday03.jpg'
	];
	$('body').css({'background-image': 'url(sites/all/themes/thebga/images/bg-body/' + bgimages[Math.floor(Math.random() * bgimages.length)] + ')'});
    });
})(jQuery);

Note the JavaScript closure around

$(document).ready(function()

more info on that here: drupal.org/node/171213.

Put your background images in /sites/all/themes/thebga/images/bg-body/. The bg-body directory is optional, I created it to keep the background images separate from the other images used in the theme.

Add this code to the page-backgrounds.css (/sites/all/themes/thebga/css/page-backgrounds.css).

body {
    /* background color + default image (in-case random-bg.js fails) */
    background: #003c00 url('../images/bg-body/ovl_2011_dos-equis_sunday.jpg') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Open the theme .info file and after

; Optionally add some JavaScripts to your theme.

add this line to load your javascript file:

scripts[] = js/random-bg.js

That is it! Every time the page is refreshed, a random background is loaded using a jQuery css modifier.

Published by

Jim Frenette

Web Developer - views here are my own except those taken from people more clever than me.