Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JS Random Image Insert to div

Status
Not open for further replies.

cfgcjm

Programmer
Oct 30, 2007
21
US
I'm trying to have a random image be shown in a div on my page. I want my JS in an external file. Below is what i have but it's not working. Any help would be great

Code:
<script type="text/javascript">
var rand_no = Math.random();
var rand_no = rand_no*5;
rand_no = Math.ceil(rand_no);
var imageCode='<img src="'+ rand_no+ '.gif" alt="" height="10" width="10" border="0">';
document.getElementById("main").innerHTML = imageCode;
</script>
 
You're initializing your rand_no variable again after you get the random number, losing the original value. You'll create an error and get 'undefined' doing that. Why not stick the whole random number generation into one line?
Code:
var rand_no = Math.ceil(Math.random() * 5);
This looks a lot like a homework assignment, and not the way I'd write the code to insert an image.

Lee
 
May I ask how you would recommend doing it? This is the simplest example i had found...
 
My issue is still getting the code into a div, not really getting the image
 
Then how about showing us your REAL code.

real code = real answers
contrived code = innaccurate answers

Lee
 
[1] The correct questions are
[1.Q1] How do I put the script in an external file if I want my JS in an external file.
[1.Q2] Why document.getElementById("main") is null or not an object?

[2]
[2.1] You put the reference to the external file in the page.

[tt]<script type="text/javascript" src="somename.js"></script>[/tt]

[2.1.1] Inside the external js (somename.js), _[blue]no[/blue]_ <script> tag.

[2.2] You have to wait the rendering of control of id "main" to complete before referencing it. Hence, you should not use that kind of barely exposed script lines (I assume correct) like that. You should put it to something like a function and assure its execute at an appropriate timing, like after window is loaded.
[tt]
//in the external js (somename.js)
[blue]function x() {[/blue]
var rand_no = Math.random();
rand_no = rand_no*5;
rand_no = Math.ceil(rand_no);
var imageCode='<img src="'+ rand_no+ '.gif" alt="" height="10" width="10" border="0">';
document.getElementById("main").innerHTML = imageCode;
[blue]}[/blue]
[blue]window.onload=x;[/blue]
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top