...

View Full Version : Unobtrusive bg randomize



buildrebuild
01-07-2007, 02:42 PM
Hi,
I need help randomizing the background image. I have tried but nothing seems to work. Here is what I have so far and it works, but this is just a single image.
PS This has to stay unobtrusive!

<script language="javascript">
function setStyles(el, css) {
var l = el.length;
if (typeof l == 'undefined') {el = [el]; l = 1;}
for (var i=0; i<l; i++) {
for (var s in css) el[i].style[s] = css[s];
}
}

window.onload = function() {setStyles(document.body, {background:'url(images/studio.gif) repeat-x top'});
}
</script>

Thx everyone,
CB

BonRouge
01-07-2007, 04:15 PM
Any reason not to do it with php? http://bonrouge.com/br.php?page=faq#randombg (having said that, there's a javascript example in there too).

buildrebuild
01-07-2007, 06:11 PM
Thanks for that. I already know the php way. It's just the person I'm doing this for actually doesn't have php on their server...lol

I've nearly got the javascript thing sorted. All I need to know is how can I get the javascript taken out of the body element?

I can use set Attribute because of IE so I had to use this and it looks messy even though it works. Is this still unobtrusive js even though it's contained within the body tag?

<body <script language="JavaScript">

<!-- Begin
document.open();
document.write("<BODY BACKGROUND='"+image+"' TEXT='"+text_color+"'>");
document.write("<CENTER></CENTER>");
// End -->
</SCRIPT>>


Best,
CB

BonRouge
01-08-2007, 02:27 AM
How about this? http://bonrouge.com/demos/js_rand_bg.htm


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>js_rand_bg</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
* {
margin:0;
padding:0;
}
body {
background-color:white;
}
</style>
<script type="text/javascript">
function randBg() {
var bg= new Array(3);
bg[0]='wine.jpg';
bg[1]='whisky.jpg';
bg[2]='beer.jpg';
var ran_unrounded=Math.random()*2;
var rand=Math.round(ran_unrounded);
var theBg= 'url(images/'+bg[rand]+')';
document.body.style.backgroundImage=theBg;
}
window.onload=randBg;
</script>
</head>
<body>

</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum