Friday, October 31, 2008

Image rotating in Drupal

Here's the poor man's image rotating approach for a Drupal site (this simple technique would work for other sites as well, provided you can generate a random number betwen X and Y). It is a very simple CSS-based with some random number generation for creating a different CSS class name for the header image.

NOTE: I'm displaying images as a background of a #header DIV.

Place some images inside your Drupal's current theme's images subfolder (that should be /[drupal root]/sites/all/themes/[your-theme-name]/images/headers/). I've placed mine in the subfolder headers where I keep all header images.

Its probably a good idea to name them similarly - header1.jpg, header2.jpg, etc.

Edit your stylesheet for the site and add one line per every image you have in the images/headers/ subfolder:
{ background:url(images/headers/header1.jpg) no-repeat;}
{ background:url(images/headers/header2.jpg) no-repeat; }
// ... add more with the same pattern
Edit your page.tpl.php and generate a dynamic class name for the #header DIV (which displays the header image), using a random number generator with a new CSS class name. The resulting code would be:

<div id="wrapper">
srand ((double) microtime( )*1000000);
$random_number = rand(1,10);
<!-- start #header -->
<div id="header" class="header-<?php echo $random_number; ?>">

NOTE: I'm using rand(1,10) to create random numbers between 1 and 10. Adjust as appropriate for your setup.

That's it. Once you open the page you'll get the #header DIV to have class="header-1" ... until class="header-10" in, hopefully, random manner.


Anonymous said...

Excellent thoughts Samir !

I have a got very basic query for the style.css and page.tpl.php file. At which position should I copy & paste this code?

FYI, I am using the whitejazz drupal theme.

Secondly,I have created this path whitejazz\images\headers. I have named the files like image01.png, image02.png etc.

sjusic said...

Anonymous: within CSS file you can place it anywhere you like.

For the .tpl.php file, make sure you place the snippet just before the area where the header image is supposed to be happening (in my example I've used the "wrapper" div to start the code which sits right below the BODY tag). Hope this helps.