PDA

View Full Version : Complete Newbie question regarding getelementbyid


ludootje
11-27-2005, 01:04 AM
Hi all,

Before flaming me that I'm doing something stupid: I am a Complete newbie to Javascript. PHP is my thing, but there are some matters which need to be tackled by means of Javascript. So... Here's my situation. I want to implement an "image rotator", which puts a new image (taken from a series of, say, 3) every so many seconds.

1) I have put some (copied...) stuff in myjavascript.js :

// JavaScript Document
var i;
var intervalle=3000;
var img = new Array();

function rand_number(n)
{
var x;
x=Math.round(Math.random()*100);
x%=n;
return x;
}

function boucle_images()
{
img[0]='<a href="http://somewhere1.com"><img src="pic1" border=0 width=140 height=200>Text 1</a>';
img[1]='<a href="http://somewhere2.com"><img src="pic2" border=0 width=140 height=200>Text 2</a>';
img[2]='<a href="http://somewhere3.com"><img src="pic3" border=0 width=140 height=200>Text 3</a>';
var nombre_total_images = 3; -->
if (i == nombre_total_images - 1) {
i = 0;
} else {
i = i + 1; }

boucle.innerHTML=img[i];
setTimeout("boucle_images()",intervalle);

2) In my main document, index.php, I wrote this:

- in the head:
<script type="text/javascript" src="http://so-and-so.com/myjavascript.js"></script>

- in the body onload:
<body bgcolor="#FFFFFF" onLoad="boucle_images();">

- and then, somewhere on that index.php:
<div id="boucle"></div>

3) But...
- In IE, this simply works. No Javascript errors, everything fine.
- In Netscape, nothing happens: no errors, but also no picture is shown.
- In Firefox, no picture is shown, but I get a "Javascript error" when I open the Javascript console. The message reads: "boucle is not defined", and a reference to my .js file, to the line: boucle.innerHTML=img[i];

My question: how can I get this thing to work? In a previous attempt, I got a recommendation to use "getElementById", but, umm, that sounded like Latin to me. Is there a good soul out here who can get my thing to work - also in Firefox, I mean? And why 'the hell' does it work in IE ??

I do hope someone can help me out... Thanks a ton!!!

Ludo

_Aerospace_Eng_
11-27-2005, 01:10 AM
Pay attention to what it tells you. boucle is undefined. Where in your script do you define it?
change this
boucle.innerHTML=img[i];
to this
document.getElementById('boucle').innerHTML=img[i];
Something that might be happening is the div isn't created yet by the time the setTimeout runs. And your question about why it works in IE, ha thats funny. IE will run almost anything. It really doesn't care.

ludootje
11-27-2005, 08:40 AM
Thanks Aerospace, you saved me a "crazyfying" Sunday, looking for something which I don't understand. But your hint made everything work, in IE, Netscape and Firefox.

Ludo