Jump to content

Random CSS div background?


Recommended Posts

can you add javascript to a css file?instead of that can you have a random css file loaded? each one could have a different div background?
You could use a JavaScript file to tell the page to load a random CSS file.java script:
function loadCss(){numberOfBackgrounds=4; //starting at 0iCss=Math.floor(Math.random()*numberOfBackgrounds);strCss=iCss+".css";strCss="<link rel=\"stylesheet\" href=\""+strCss+"\" type=\"text/css\" />";o=document.getElementById('cssDiv');o.innerHTML=strCss;}

Then put a DIV container at the start if your page:

<div id="cssDiv"></div>

And use

<body onload="loadCss();">

to make sure that the HTML is loaded into the element after the element is loaded on the page...It's not the cleanest way of doing it, since you end up with the "link" element inside the body of the page, but it works...And you just make a few CSS files, number from 0, and with the appropriate background stuff.PS: You can't add Javascript to a CSS file... well.. you can, but it'll either read it as javascript or as css... and since you should tell it what type of file it is when you link it, then it'll mess things up, really.

Link to comment
Share on other sites

It's not the cleanest way of doing it, since you end up with the "link" element inside the body of the page, but it works...
Can't you place it in the head instead though?
<head id="cssDiv">

although then you should use


so you don't overwrite the rest of the head elements innerHTML.

Link to comment
Share on other sites

Another way of doing it, which might be better is using the style property of the body tag...

<script type="text/javascript">function loadBg(){numberOfBackgrounds=4;i=Math.floor(Math.random()*numberOfBackgrounds);theBody=document.getElementsByTagName('body')[0];theBody.style.background="URL("+i+".jpg)";}</script></head><body onload="loadBg();"></body>

then you have your images numbered 0-n instead of using stylesheets... but you'd have to use CSS to set the other properties. Background color, repeat, attachment and position.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...