...

View Full Version : Set two divs to have same randomly generated background image



dylanbaumannn
06-28-2012, 05:21 PM
Hello!

I'm looking for a relatively simple solution to a problem I've encountered. I have two divs on a page that need to be have random backgrounds (this isn't an issue), however I need a way to set BOTH of these divs to the same random background.

The best way I can think to do it is to generate the random image, store it in a variable and then call the variable as a background image for both of the divs.

I'm relatively new to jQuery and javascript, so while I understand HOW to do it, i'm not exactly sure syntax-wise how to accomplish it.




<script language="JavaScript">
var randnum = Math.random();
var inum = 4;
// Change this number to the number of images you are using.
var rand1 = Math.round(randnum * (inum-1)) + 1;
images = new Array
images[1] = "img1.jpg"
images[2] = "img2.jpg"
images[3] = "img3.jpg"
images[4] = "img4.jpg"
var image = images[rand1]
</script>


Then alter the background using a css modifier
(this alteration code might not be correct, THIS IS NOT THE ISSUE, this is just an example to show my intent)


<script language="JavaScript">
$('div.randomBackground').css({
'background': image;
});
</script>


I'm unsure how to store the random image in a variable and then call it inside a div....

Can anybody help me?

Many thanks!

Philip M
06-28-2012, 05:36 PM
You have your image stored in a variable already!

var image = images[rand1];


All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

dylanbaumannn
06-28-2012, 05:51 PM
You have your image stored in a variable already!

var image = images[rand1];

All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.


oh hey!

Haha, ok, so when calling that inside of the divs would i just use that CSS replace and call it like I did in that example?




<script>
var image = "black"
$('div.randBg').css('background', ' +image+ ');
</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum