Tutorials
Randomize… Pretty much anything!
-
Randomize… Pretty much anything!
Posted on April 11, 2006
Written by
Valerie (view more by Valerie)
Comments (0)
Filed under PHP, Tutorials
So… you want a random background image? Or a random stylesheet, even? Try this out – it’s quick, easy – and will use PHP and CSS.
First you, of course, should be able to use PHP on your site. You should also know a little bit about CSS. Those are the two things this technique will use. There are numerous ways this can be accomplished but this is the way I am currently using it on my blog site.
First, I have the area where I want the images to be randomized. This is my header image. I have a div for that and it has both an ID and a Class. This is what it looks like before I randomize it:
<div id="random" class="random"> </div>
I use the ID to define all the basics and styles other than the image to get that out of the way and free the Class up for the random background image.
Next, add in your random PHP snippet that will essentially change the Class with each page load:
<?php echo(rand(1,X)); ?>
So now the whole thing looks like this:
<div id="random" class="random<?php echo(rand(1,X)); ?>"> </div>
Just change that “X” to however many images you plan to have be it 5 or 20, it is your maximum value that you want outputted. When you load the page, that random PHP snippet will pick a number between 1 and that number, so you will end up with class=”random2″ or class=”random5″ and so on. Of course, if you want to get technical, you can also change that “1″ to something, so as to randomize between, say, 3 and 7, etc.
Now you need to tell it what to do with those classes. In your CSS, define what each and every one of those classes will do. If you’ve got three images you want to rotate between, you might do something like this:
.random1 {background: url(images/image1.jpg);}
.random2 {background: url(images/image2.jpg);}
.random3 {background: url(images/image3.jpg);}
See? Easy!
That’s just the bare minimum, you could even use the CSS to randomize anything: different colored text, different margins, padding, borders, etc. If you really wanted to waste a lot of time, you could use that PHP snippet in your call for a stylesheet and load a completely different stylesheet each time, you would just start your stylesheet code and put the PHP code somewhere inside the href call for the stylesheet and have your stylesheets appropriately named. Of course, that might make your visitors want to pluck out their eyes, but you get the idea!
Comments
Comments are closed for this entry.