View Full Version : Image display to number range

01-16-2012, 10:32 AM
So I've got my code ready to generate a random number between a certain range and printing it out in text. What I'm trying to accomplish with this code is to print the actual image as well as the text.

I'm aware that there is an error in my document.write line, and that it's not the best solution. I was hoping for some suggestions to change/improve this last bit. Thanks in advance!

<script language="javascript" type="text/javascript">
var ranges = [
{ from: 11, image: "image4.jpg" },
{ from: 1, image: "image3.jpg" },
{ from: -9, image: "image2.jpg" },
{ from: -20, image: "image1.jpg" }

var random_num = (Math.round((Math.random()*41)+-20));
var image = "default";

for(var i = 0; i < ranges.length; ++i) {
if(random_num >= ranges[i].from) {
image = ranges[i].image;
document.write("Text: " + random_num + " Text, " + " Image: = " + image);
document.write('<img src="images/' + ranges[i].image);
CLICK <a href="javascript:history.go(0);">REFRESH or F5</a> FOR A RANDOM IMAGE on NUMBER-RANGE.

Philip M
01-16-2012, 11:22 AM
You seem to be making heavy weather of this. Keep it simple:-

<img id = "myImage" src = "default.jpg">

<script type="text/javascript">

var random_num = (Math.round(Math.random()*41)-20);
var image = "default.jpg";
if (random_num >= 11) {image = "image4.jpg"}
else if (random_num >= 1) {image = "image3.jpg"}
else if (random_num >= -9) {image = "image2.jpg"}
else if (random_num >= 11) {image = "image1.jpg"}
document.getElementById("myImage").src = image;


Avoid using document.write(). document.write statements must be run before the page finishes loading. Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page (including the Javascript that triggered it). So document.write is at best really only useful to write the original content of your page. It cannot be used to update the content of your page after that page has loaded.

If you wish you can wrap the whole script in a function, and call it onclick of a button.

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

01-16-2012, 12:35 PM
thank you very much for your input! It works like a charm. :thumbsup:

I used your code and added to the end:

alert("Text: " + random_num + " Text, " + " Image: = " + image);

to show me the image's description as well.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum