File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes HTML, CSS and JavaScript and the fly likes Undefined Array Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Undefined Array Problem" Watch "Undefined Array Problem" New topic

Undefined Array Problem

Blaise Harriman

Joined: Apr 12, 2011
Posts: 1
I'm new to javascript and have a small but annoying problem with an array. The script rotates a randomly selected banner from an array and changes the banner every few seconds. The problem is that when the page is first loaded the word 'undefined' displays next to the first banner. When the second banner is displayed everything works fine.

Here is the function I am using

function randomBanner()

var myBanners=new Array(3);
var i = Math.floor(Math.random() * 3);

myBanners[0]="image 1";
myBanners[1]="image 2";
myBanners[2]="image 3";

document.getElementById('banners').innerHTML = myBanners[i];

setTimeout("randomBanner()",5000 );//5000 = 5 seconds


and here is the html code

<script type="text/javascript" src="rotator.js"></script>

<div id="banners">
<script type="text/javascript">document.write(randomBanner());</script>

I have tried declaring the variables and even the array itself outside the function to no avail. I have set up a test page so you can view the problem here

Please can someone help?
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Hi and welcome to the JavaRanch.

Keep in mind that Java != Javascript. They are 2 different languages. I've moved your topic to a more suitable forum.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
I agree. Here's the link:
subject: Undefined Array Problem
It's not a secret anymore!