Reputation: 4999
Okay, So I'm trying to have this code display text at different intervals in a specific div. "text1" appears in the div normally but after a few secs the page loads everything disappears and the text is visible but on a blank page.
Could someone help me so text2 and text3 appear in the div with the rest of the content.
Thanks.
<script type="text/javascript">
function typeText1()
{
document.write('<p style="color:blue;">text1</p>');
setTimeout( "typeText2();", 1000);
}
function typeText2()
{
document.write('<p style="color:blue;">text2</p>');
setTimeout( "typeText3();", 3000);
}
function typeText3()
{
document.write('<p style="color:blue;">text3</p>');
}
typeText1();
</script>
Upvotes: 0
Views: 299
Reputation: 186562
That's because you are using document.write
. It rewrites over the entire document. Use methods like appendChild
or replaceChild
or even .innerHTML
.
For succinctness I'll just use innerHTML as an example:
<div id="thing"></div>
<script>
(function() {
var thing = document.getElementById('thing');
function typeText1() { thing.innerHTML = '<p>text1</p>'; setTimeout( typeText2, 1000 ); }
function typeText2() { thing.innerHTML = '<p>text2</p>'; setTimeout( typeText3, 1000 ); }
function typeText3() { thing.innerHTML = '<p>text3</p>'; }
typeText1();
})();
</script>
Edit #2:
<!doctype html>
<html>
<head>
<title></title>
<style type="text/css" media="screen">
* { margin:0; padding:0; }
.one { color:red; }
.two { color:blue; }
.three { color:yellow; }
</style>
</head>
<body>
<p id="thing"></p>
<script>
(function() {
var thing = document.getElementById('thing');
function typeText1() { thing.innerHTML+= 'text1'; thing.className+= ' one'; setTimeout( typeText2, 1000 ); }
function typeText2() { thing.innerHTML+= '<br>text2'; thing.className+= ' two'; setTimeout( typeText3, 1000 ); }
function typeText3() { thing.innerHTML+= '<br>text3'; thing.className+= ' three'; }
typeText1();
})();
</script>
</body>
</html>
Upvotes: 5
Reputation: 1190
Simple example using jQuery:
$(function() {
$("body")
.append("<p style='color:blue;'>text1</p>")
.delay(1000)
.append("<p style='color:blue;'>text2</p>")
.delay(1000)
.append("<p style='color:blue;'>text3</p>");
});
If you have to do this lots of times then it might be better to set up a loop. Equally, if you have a lot of content whose appearance you want to delay then it might be better to put it in the HTML, hide it when the page loads, then use Javascript to display it.
Upvotes: -2