Writing to a document
You can create an HTML document 'on the fly' with JavaScript using the document.write()
method. Normally, you must open a new document first. Then you may write to that document, and finally you must close the document so that the Browser can stop trying to load it. Here is an example:
document.open()
document.write("Hello There")
document.close()
When I create a new window, I am also opening a new document. So I can write to a new window with this series of commands.
NewWindow = window.open("","","width=200,height=200")
NewWindow.document.write("Hello There")
NewWindow.document.close()
The document.write()
method can contain either text or a variable inside the perentheses. The following example creates a variable, then writes the variable to a new document.
SampleText = "Hello there, " +
"It's nice to see you again."
NewWindow = window.open("","","width=200,height=200")
NewWindow.document.write(SampleText)
NewWindow.document.close()
I can even include HTML tags in the document.write() statement. Like this:
NewWindow = window.open("","","width=200,height=200")
NewWindow.document.write("<CENTER><H1>Hello there</H1></CENTER>")
NewWindow.document.close()
With just a little creativity, you can have JavaScript create fully formatted web pages on the fly.
function MakePage(name, town, roommate, age) {
var content =
'<HTML>
<HEAD>
<TITLE>' +
name +
'\'s Page</title>' +
' </HEAD>
<BODY background = "images/space.gif"
text = "yellow"
link = "#FFBBBB"
vlink = "#FFBBBB" > ' +
' <FONT COLOR = "4EEA6C" > < center > < h1 > ' +
name +
'\'s Page</h1></center></FONT>' +
' <IMG ALIGN = Left SRC = "http://images.webteacher.com/javascript/images/heart.gif"
WIDTH = "72"
HEIGHT = "72" > Hello, and welcome to my page.I live in ' +
town +
'and I am ' +
age +
'years old.' +
' <P> ' +
town +
'isn\ 't a bad place to live, if you can stand ' +
roommate +
'\'s cooking <P> ' +
'Some people think they\ 're so cool just because they created a home page. <BR> ' +
'They have fancy backgrounds and colors, but they just go on and on with nothing to say. <BR> ' +
' <A HREF = "http://www.yahoo.com/" > Click Here to search Yahoo < /A>
<--Boy, there\ 's a link I never' +
' would have found on my own. Some people\'s pages are so boring I think my computer could do ' +
' a better job with a 10 line program. '
document.open()
document.write(content)
document.close()
}