Random CSS with JavaScript

I was just working on a site that required a random header image. I’ve done random images with JavaScript before, but the script I’ve used writes out an image tag. This site was built using a CSS background-image for the header so I needed something a little different. I came up with the following after a bit of googling around and trial and error. If you have suggestions to improve this, please feel free to share in the comments. :-)

First, put the following code into a file called random_styles.js:

<!-- Begin
var random=Math.floor(2*Math.random());
random=random+1;
style='<!-- @import url( css/' + random + '.css ); -->';
document.write('<style type="text/css" media="screen">');
document.write(style);
document.write('</style>');

// End -->

Where the “random” variable is set, change the number 2 to match the total number of stylesheets you will switch between.

Where the “style” variable is set, adjust if your css path is different from mine.

(You don’t really need to add 1 to random, but I did that so the first number can be equal to the number of stylesheets…)

Then, in the head of your html page, just include the file random_style.js like so (with the src path altered to suit of course):
<script language="Javascript" src="js/random_style.js" type="text/javascript"></script>

Note: you must put it after the main stylesheet!

You also need to create one css file for each style. So in my case I had a main stylesheet for the site, which set a default background image in case javascript was turned off. Then, in a file called 1.css I set the same background image again. In another file called 2.css I set the image to be different.

I’m sure this could be improved, so like I said, feel free to share your comments.

Write a comment





Previous post: « How to change your WordPress RSS Feed to full posts
Next post: In praise of days off »

Recently Written:

Categories

RSSSubscribe to RSS Feed

About

Tzaddi Gordon
link to linked in profile

Zodomatica is the personal site of Tzaddi Gordon, a web designer from Roberts Creek, BC, Canada. I'm passionate about design that balances form and function. I design, code, and hack other people's scripts. Lately I groove on WordPress as a CMS.
My portfolio