1

needing some help. I have two divs that I need to fill with images. The images can't be random as div 1's image needs to correspond to div 2's. I've been playing around and have managed to get the javascript working to this point. The problem is I need the script to write to the div backgrounds rather than fill the div with an image.

<script>
var random = Math.random();
function random_imglink(arr){
var ry = Math.floor(random*arr.length);
document.write(
'<img src="'+arr[ry]+'" border=0 class="two">'
);
}
var myimages = [
"img1.jpg", "img2.jpg","img3.jpg"
 ],
myimagesA = [
"img1b.jpg","img2b.jpg","img3b.jpg"];

</script>
<div><script>random_imglink(myimages);</script> </div>

<DIV><script>random_imglink(myimagesA);</script></div> 
Tallulah
  • 39
  • 4
  • Pretty much 90% of text and title of this post have nothing to do with real question, I'd suggest editing it and throwing out irrelevant parts. – Oleg V. Volkov Aug 28 '12 at 08:12

3 Answers3

1

Your code needed quite an overhaul. This is what it should look like after being fixed:

<div id='a'>A</div>

<div id='b'>B</div>​
<script>
var random = Math.random();
function random_imglink(arr, id){
    var ry = Math.floor(random*arr.length);
    document.getElementById(id).style.backgroundImage = "url('" + arr[ry] + "')";
}
var myimages = [
    "http://img1.jpg.to"],
    myimagesA = ["http://img1b.jpg.to"];


random_imglink(myimages, 'a');
random_imglink(myimages, 'b');
</script>

Demo

Some Guy
  • 15,854
  • 10
  • 58
  • 67
0

To set an image as the background of an element you can use this:

document.getElementById("myDivId").style.backgroundImage = "url(/path/to/img)";

In your code, you could do it something like:

var random = Math.random();

function random_imglink(divId, arr){
    var ry = Math.floor(random*arr.length);
    document.getElementById(divId).style.backgroundImage = "url(" + arr[ry] + ")";
}

var myimages = ["img1.jpg", "img2.jpg","img3.jpg"],
   myimagesA = ["img1b.jpg","img2b.jpg","img3b.jpg"];

random_imglink("firstDiv", myimages);
random_imglink("secondDiv", myimagesA);

html:

<div id="firstDiv"></div>
<div id="secondDiv"></div> 
Asciiom
  • 9,867
  • 7
  • 38
  • 57
0

Smallest possible change of the current code; make the function write a div tag with a style attribute instead of an image tag:

document.write('<div style="background:url('+arr[ry]+')">');

Put the script where you want the start tag:

<script>random_imglink(myimages);</script> </div>
Guffa
  • 687,336
  • 108
  • 737
  • 1,005