Edit: If you do not have access to the PHP source code on your site, try this random background image script generator
Here's something I've been playing with lately to add a little bit of visual dynamic interest to sites that don't have frequently changing content. The concept is not new – use image rotation to display random images on each page load. No great problem there, simply use a server-side script to select a random image. But what if your images are not content, are purely presentational, and are (read 'should be') background images?
Using PHP to retrieve a random image from a folder, we can generate dynamic CSS declarations through the page headers. This means we can change background images randomly on page load, and we can control which images are available by adding or removing them from the images folder.
First up we need to create the PHP script that will get the images from a folder, select a single image at random, and write the CSS declaration to the page header. Everything you need is in the following scripts, and all that needs customising is the path to your style and image folders. Copy and save this file as dynamic_css.php.
http://www.thought-after.com/2006/05/26/css-random-background-image-rotation/
This file will display a random background image to any element targetted through a CSS id.
1) Place this file in the same location as your sites main stylesheet file.
2) In the head section of each page place the following @import statement.
@import url(/path/to/dynamic_css.php)
NOTE: the import must occur after all other style sheet links, imports and declarations to avoid this dynamic style being over-written.
3) Create a folder to hold the images to be used for the random backgrounds.
4) Assign values to the following variables to complete the setup
$imgFolder : the path from the sites root to the image folder created at 3 above example:
$imgFolder = "/images/random-images/";
$element : the css ID of the element to apply the background image to example:
$element = "header";
5) That's it!! ***/
// Set up
$imgFolder = "/images/random-images/"; // the path from the sites root to the image folder created at 3 above
$element = "header"; // the css ID of the element to apply the background image to
// That's it!! Nothing below this line needs to be changed
$img = null;
// build up the path to the image folder
if (substr($imgFolder,0,1) != '/') { $imgFolder = '/'.$imgFolder; }
if (substr($imgFolder,-1) != '/') { $imgFolder = $imgFolder.'/'; }
$path = $_SERVER['DOCUMENT_ROOT'] . $imgFolder;
// populate an array to hold valid file type extensions
$extList = array('gif','jpg','jpeg','png');
// create an array to hold the list of image files
$fileList = array();
// open a handle to the directory
$handle = opendir($path);
// loop through the contents of the directory
while ( false !== ( $file = readdir($handle) ) ) {
// get the info for each file
$file_info = pathinfo($file);
// check that the file in in the allowed extensions array
if ( in_array( strtolower( $file_info['extension'] ), $extList) ) {
// add the file to the array
$fileList[] = $file; }
}
// close the handle to the directory
closedir($handle);
// if we have at least 1 file in the list
if (count($fileList) > 0) {
// select a random index from the file list array
$imageNumber = time() % count($fileList);
// assign the filename for that array index to the $img var
$img = $imgFolder . $fileList[$imageNumber];
$css = "#$element { background-image: url('".$img."'); }\n";
// tell the browser what we're sending
header('Content-type: text/css');
// and write out the css
echo $css;
}
?>
Now in the head of our HTML page import the dynamic css:
If you have set up your path correctly, which I'll admit always catches me out, then each page load should see a random background image displayed in the element specified in the dynamic CSS.
Obviously this method can be extended and modified to suit you exact circumstances. I currently pass page identifiers through the import statement as part of a querystring which then query a database for specific content, meaning I can specify a range of images for use on each page, and on each element on that page. The possibilities are seemingly endless, and only limited by your imagination.
Edit (16/07/2007): I've tidied the script up a little to make it easier to implement. Just a couple of documented steps to follow, and thats' it!!
Tags: dynamic css, dynamic style, random background image, random backgrounds, random images
-
-
If I wanted to use this script to add random backgrounds to more than one div, how would I do so without having to have multiply copies of your scripts to put the bg's in certain div's.
Thanks,
-
Thanks for sharing this! I think there's a shorter way to do this, but I just don't know how. Hmmm..
-
Hi,
Firstly I must say how good the free script is that is generated… works a treat!I found your free script after searching the internet for 2 days solid and trying various others.
The thing is I have been looking for a script that does what yours does but changes the background image every few seconds and not on page load or refresh.
I'm on my third day now looking at codes; CSS, Javascript, php, html you name it, chopping bits out of one and trying them in another but still can't achieve the desired effect.
It's seems simple enough to do for foreground images and there are plenty of options to choose from on the internet, but nothing for background images!!!
I have a quick search facility on my proto-type web which contains a couple of drop-down menus and a min/max amount input box.
I want to have a background image behind this which rotates between several images but can't for the life of me achieve it.
I need to call the script that does it from within a <td tag. for example <td id="whatever"
or <td width="700" height="400" background-img: url="a php file with rotating images in
If this is possible?
Is there any chance you could adapt the script which is generated free to rotate images every few seconds or an amount of time chosen?
I think if you can you will boost traffic to this site 10 fold as I have come across hundreds of other wanting to achieve the same thing while I have been searching.
Pleaaaaaaaaaaaasssssssssssssssseeeeeeeeeeeeeeeeee
-
Hello All,
Well, I found this PostNuke-Zikula CMS and I would love to have my background image changing, at every time the page refresh or by after some time. But, I can not find any .HTML file to add the code, and as you will see, I am clueless on this programming and code stuff.
The only thing I found on the Zikula folders, is a file where the background image is loaded is named Style.css and the line say:
body {
.
.
.background-image: url(../images/background.jpg);
.
.
. etc.So, Can any one help me with this?
Thanks!
-
Hi. I'm currently an IT student doing a school project.
I've tried to implement your code into my website but somehow, I can't get it to work.
Is it okay if you could spare some time to take a look at my coding? -
Thanks for this! It's a great help. Just what I was looking for!
-
hi, i hv been trying but it seems not working. not sure if i missed any step..
can help me to look at this scripts?
http://newfields.chameleon.com.my/randomtry/a.html -
I really want to use this in a Wordpress theme…which has it's own header.php file, so that's where I'm putting the @import code like this:
@import url(dynamic_css.php);
I can't get it to work, and it may be because I don't understand paths very well….I've no idea where the root of my site is, especially as I'm testing this on a MAMP localhost installation, not online. The URL of my (local) site is:
http://localhost:8888/wordpress/
but if you followed the file structure to dynamic_css.php, it would be something like this:
/htdocs/wordpress/wp-content/themes/snowblind/
So I've no idea what the path 'from the site's root to the image folder' is!
Any help appreciated.
Hugh
-
I'm also trying to use it in my Wordpress theme, which also has it's own header.php. I feel I did everything as directed above, and I even tried customizing it a bit, but nothing seems to work.
Does anyone know how to get this, or any other random background image generator to work with Wordpress. I can't seem to find anything.
-Trevor
-
As Pink Floyd said……"Is there anybody out there?"…….
???
-
-
shweet!
-
Hello,
Hopefully someone can help me. I'm trying to use this script to rotate the overall site background. I've tried everything I can think of to get this to work. Could my problems be related to the fact that the body section of the CSS file doesn't start with a # (as seen below)?
BODY {
background: #012d4a;
background-image: url(img/background3.png);
background-position: top center;
background-repeat: no-repeat;
background-attachment:fixed;
font-size: 1em;
font-family: verdana;
margin: 0;
}This is the background image that I am trying to rotate… is it possible? Any help would be greatly appreciated!
Thanks
Chris
-
Hello,
Yup, I have the @import directive in place. If you'd be willing to check it out, that would be great. My site is http://hasslefreegaming.com/v2/index.php. I'm new to css and php, the site is a work in progress
Thanks again!
-
Hello.
I was able to accomplish the random background with a different method, it's not as dynamic as this one, I have to put the file names in an array. since I'll only have a couple images, that is fine.
Thanks!
Chris
‹ Previous · 1 · ... · 5 · 6 · 7

153 comments
Comments feed for this article
Trackback link: http://www.thought-after.com/2006/05/css-random-background-image-rotation/trackback/