below is my external javascript code and testing page.
for this im just using settimeout to loop increment and write out a value.
on the first loop everything works corrrectly.
on the second loop everything gets erased and only displays the text i wrote.

i can run other scripts fine like this. (ie changing the background randomly)
why does document.write erase my page? im just beginning to learn this scripting language.
Thanks

var iCount = 1;
function Main(){

Writer();
Loop();

}

function Writer(){
document.open();
document.write(iCount++);
document.close();
iCount++;

}

function Loop(){
return window.setTimeout(Main,1000);
}

Main();
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Untitled Document</title>

</head>

<body>

<p>
<script src="da.js" type="text/javascript">
</script></p>
</body>
</html>

Recommended Answers

All 3 Replies

ok i understand now that you cant do a document.write to a page that is already loaded or it clears it. so now im trying to work with a DOM. if i click on the element it seems to call the function. but i want this to loop in the backgroup. im trying to make a simple typewriter effect. argh! here is what i have now

my javascript console says "myDiv" has no value

function Main(){
Writer();
Loop();

}

function Writer(){
document.getElementById("myDiv").replaceChild(
  document.createTextNode("Good evening"), 
  document.getElementById("myDiv").childNodes[0]);

}


function Loop(){
return window.setTimeout(Main,1000);
}

Main();
<html>
<head>
<title>argh!</title>
<script type="text/javascript" src="da.js"></script> 
</head>

<body>
<div id="myDiv">change</div>
</body>
</html>

ok yeah i figured it out. i have to make it start in the body on load.

is there anyway to start it from the external script without calling it from the body onload?

Yes... you can include a <script></script> anywhere in your page. It doesn't have to be in the HEAD, that's just a good convention.

But, you have to start it somewhere, and <body onload=...> is the right spot to do it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.