In this snippet, when 'FirstText'
is written, then rest of first line is skipped. Then 'SecText'
is written on the 2nd line:
<pre>
<script>
function text(){
document.write("FirstText \n SecText");
}
text();
</script>
</pre>
But when I use setInterval()
on this function, words are written next to each other (lines are not skipped).
Any suggestions?
In this snippet, when 'FirstText'
is written, then rest of first line is skipped. Then 'SecText'
is written on the 2nd line:
<pre>
<script>
function text(){
document.write("FirstText \n SecText");
}
text();
</script>
</pre>
But when I use setInterval()
on this function, words are written next to each other (lines are not skipped).
Any suggestions?
Share Improve this question edited Jan 8, 2017 at 20:25 Kishore Bandi 5,7212 gold badges34 silver badges54 bronze badges asked Jun 2, 2013 at 19:18 MattMoulsonMattMoulson 451 gold badge1 silver badge4 bronze badges 2- Do you need another \n after SecText? – Peter de Rivaz Commented Jun 2, 2013 at 19:20
-
you need a <br> :
document.write("FirstText <br /> SecText");
– Utopik Commented Jun 2, 2013 at 19:38
2 Answers
Reset to default 8You're seeing \n
create a new line because you're inside a <pre />
tag; normally you have to use a <br />
to see a similar new line outside of <pre />
.
When you call document.write
before the page has finished loaded, the output is entered inplace; so you'll see your FirstText \n SecText
written within the <pre />
.
However, when it's called after the page has loaded (within setInterval
), the existing page is cleared before the result is written; hence <pre />
is being removed, and you're not seeing your new line any more.
As you're not closing the document
using document.close()
, successive calls to document.write
in your setInterval
are adding to the document stream opened by the first iteration of setInterval
.
You can fix this by using a <br />
rather than \n
;
<script>
function text(){
document.write("FirstText <br /> SecText <br />");
}
setInterval(text, 1000);
</script>
For more info, see https://developer.mozilla/en-US/docs/Web/API/document.write and document.write clears page
try this:
document.write("FirstText <br /> SecText <br/>");
working example:
http://jsbin./oyolod/4/