Hi,

I am trying to get a random image as a background to a cell, and have tried many ideas but none work, in desperate need for help can anybody please.

I have this in the header

<script language="javascript" type="text/javascript">
  
    var img_rnd = new Array ();
	
	img_rnd[0] = "hp-1.jpg";
	img_rnd[1] = "hp-2.jpg";
	img_rnd[2] = "hp-3.jpg";
	img_rnd[3] = "hp-4.jpg";
	img_rnd[4] = "hp-5.jpg";
	img_rnd[5] = "hp-6.jpg";
	
	var i = Math.floor(Math.random() * 6);
	
	document.getElementById("hp-random").style.backgroundImage="url("+img_rnd[i]+")";
	
	//-->
  </script>

and this on the cell

<td colspan="2" id="hp-random" height="395">

Dani AI

Generated

Common cause and quick summary (references to earlier replies)
’s problem is almost always the script running before the <td> exists in the DOM. spotted that and suggested running the code after the page loads; their example also contains a small typo (function name vs onload call). ’s suggestion to use an <img> inside the cell will work but is not the same as a random background. ’s Firefox-only failure is a classic symptom of two separate mistakes: an incorrect random-index expression and relying on a browser-created global variable for an element id.

A robust, modern client-side pattern
Place the logic after the DOM is ready, pick an index with Math.floor, preload the chosen image, then set a CSS background (using the background shorthand to include sizing and repeat control). Example:

document.addEventListener('DOMContentLoaded', function () {
  var pool = ['hp-1.jpg','hp-2.jpg','hp-3.jpg','hp-4.jpg','hp-5.jpg','hp-6.jpg'];
  var cell = document.querySelector('#hp-random');
  if (!cell) return;
  var i = Math.floor(Math.random() * pool.length);
  var p = new Image();
  p.onload = function () {
    cell.style.background = 'url("' + pool[i] + '") center center / cover no-repeat';
  };
  p.src = pool[i];
});

Troubleshooting notes and gotchas

  • The Math.round(Math.random()images.length-1) form from is wrong because of operator precedence and can produce -1 or an off-by-one — use Math.floor(Math.random() images.length).
  • Do not rely on element ids becoming globals (some browsers expose them, Firefox does not). Use document.getElementById or querySelector.
  • Relative URL resolution depends on where the style is applied: inline styles resolve relative to the HTML document; external CSS resolves relative to the CSS file. Check case-sensitive file names on the server.

Extra options
For zero flicker and smaller payloads, pick the image server-side before sending the page (as mentioned). Alternatively, assign a random CSS class (predefined background-images) for cache friendliness. For large images, optimize and consider a low-res placeholder to avoid layout shift.

Recommended Answers

All 4 Replies

Magic8Computing why do you need Javascript for this. Try keeping the script as clean as possible. If you are trying to incorporate an image into the table cell that shouldn't be too complicated, <table> <tr> <td> <img src="your image here" alt="" /> </td> </tr> </table>

commented: Duh, the words rqandom image in the thread title slipped your notice perhaps -1

as it is the code is wrong
when the javascript is declared in the head before the page is rendered the <td id='hp-random'> element does not exist, setting the attrributes of a non-existent element causes errors
a possible solution is to make the javascript a function and put the function in the onload call for the <body> tag,

<script type='text/javascript'>//langueage='javascript' is deprecated
function randomimg() {var img_rnd = new Array ();
img_rnd[0] = "hp-1.jpg";
img_rnd[1] = "hp-2.jpg";
img_rnd[2] = "hp-3.jpg";
img_rnd[3] = "hp-4.jpg";
img_rnd[4] = "hp-5.jpg";
img_rnd[5] = "hp-6.jpg";
var i = Math.floor(Math.random() * 6);
document.getElementById("hp-random").style.backgroundImage="url("+img_rnd[i]+")";
}	//-->
</script></head><body onload='randoming();'>

or to put the script, as is, after the page loads, between </body> and </html>

javascript will always look wrong, the page will load, the script will process, the background image will download and place itself
the same effect done in a server language is seamless to the user the random image is selected before the page downloads, the page source displayed only includes the current image, thew downloaded page is slightly smaller

- he wants a random image..your code will give a single fixed cell image.
@poster- try almostbobs advice,tink it shld work...u might also tink of using a light animation software such as swishmax to do an anim. instead and place it in the cell.gluck

Hi, I am trying to do a similar things, have a random image as a table background.

I've got a script that works in IE and Safari, but for some reason not in Firefox!

Here is the code I'm using:

<script type="text/javascript">
var images = new Array("image1.jpg","image2.jpg","image3.jpg","image4.jpg")
onload=function() {
var rand = Math.round(Math.random()*images.length-1)
table1.style.background="url('"+images[rand]+"')"
}
</script>

and then this is the start of my table in the body:

<table id="table1" width="1200" height="828" border="0" cellpadding="0" cellspacing="0" bgcolor="white">

Any help would be much appreciated! I can't get my head round this!

Cheers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.