PDA

View Full Version : DOM Frustration


Kentaro
07-22-2003, 02:06 AM
I want to put text from a certain element of an array inside an HTML DIV element with id="currenttext". For some reason, the document.getElementById() call does nothing (I've used document.write() calls to debug to this point). It returns null. There is nothing inside of the DIV element that I'm trying to refer to but I should still be able to add a text node to it!

Here is the file I'm working with:


<HTML>
<HEAD>
<TITLE>Ticker Javascript (DHTML)</TITLE>

<STYLE>
.tickerbox { background: #000000;
width: 400 px;
height: 30 px;
padding: 5px }
.tickertext { font: 10pt "Arial";
color: #FFFFFF }
</STYLE>
<SCRIPT>
// const interval = 1000;
itemList = ["Hello!", "I'm a ticker!", "I can change!"];
current = 0;
function changeItem()
{
// change from itemList[current] to itemList[next]
}
function startTicker()
{
/* start the ticker animation by displaying itemList[0]
and setting timeout (setTimeout) */
txt = document.createTextNode(itemList[0]);
document.getElementById("currenttext").appendChild(txt);
}
startTicker();
</SCRIPT>
</HEAD>
<BODY>
<P align=center>The following demonstrates a DOM ticker in Internet
Explorer:</P>
<DIV id="ticker" align="center">
<DIV id="mainticker" class="tickerbox" align="center">
<DIV id="currenttext" class="tickertext"></DIV>
</DIV>
</DIV>
</BODY>
</HTML>

Please help! Everytime I've tried to do something remotely fun with the DOM I've gotten nothing but frustration out of it! I've been reading specifications and tutorials for hours on end (for DOM, HTML, CSS, and Javascript). :(

mace
11-21-2003, 02:01 PM
<body onLoad="startTicker();">

tobymiller
01-21-2004, 04:44 PM
mace is right

The reason he's right is because of the way the page is drawn out. When you put javascript into the head or body of a page it gets executed as it's interpreted. Since the body elements you're referencing don't exist yet there's nothing for your function to manipulate.

By placing the code call in the body's onload event you're telling it to wait until the whole page is done loading before calling the function "startTicker". Now that everything is loaded it works as expected.