|
-
May 17th, 2012, 09:12 AM
#1
Thread Starter
Addicted Member
Javascript resets my body background
Why is the following code resets the background to white color while i have defined it black?
Code:
<html>
<head>
<title>Test Page</title>
</head>
<body bgcolor="#000000" text="#00ff00">
<font face="system">
<script language="javascript">
<!--
var i;
var timer = 0;
var speed = 500;
var mytext = "Hello World...";
document.write("<b>");
for (i = 0; i <= mytext.length; i++)
{
timer += (Math.random() * speed);
setTimeout("document.write('" + mytext.charAt(i) + "');", timer);
}
document.write("</b>");
-->
</script>
</font>
</body>
</html>
-
May 17th, 2012, 10:24 AM
#2
Thread Starter
Addicted Member
Re: Javascript resets my body background
-
May 17th, 2012, 12:33 PM
#3
Re: Javascript resets my body background
As far as I can tell, it has to do with running document.write within a setTimeout. Try changing the text of an element instead of trying to write to the entire page.
*edit*
Just realised what you're doing. I would recommend jQuery to write out text like that, as it is much simpler, but here is an example of how to do it using setTimeout.
Code:
<script language="javascript">
var i = 0;
var timer;
var speed = 500;
var mytext = "Hello World...";
write_text();
function write_text() {
if(i <= mytext.length) {
document.getElementById('test').innerHTML += mytext.charAt(i);
i++;
if(i < mytext.length) {
timer = setTimeout('write_text()', (Math.random() * speed));
} //end if
} //end if
} //end function
</script>
Last edited by kfcSmitty; May 17th, 2012 at 01:09 PM.
-
May 17th, 2012, 02:51 PM
#4
Re: Javascript resets my body background
The problem is in how document.write works. While the page is loading, there's a single document object by which your document.write calls are executing; the result of their execution will occur inline in the rendering of the document object. After the page finishes loading, if you call document.write again, it will start a new document object, which overwrites the old, already-rendered one (though once it makes this new one, it can reference it again, so multiple write calls won't continually overwrite each other).
The solution is as kfcSmitty depicted: instead of document.write, you should use a method that operates on the text of an element.
-
May 17th, 2012, 04:13 PM
#5
Thread Starter
Addicted Member
Re: Javascript resets my body background
I used a much simpler solution. I just added a div id and using innerHTML i sent the text to this id. And it works great.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|