The open() and close() methods

The open() method allows you to create a new document and write its content entirely using document.write() or document.writeIn() statements. To finish the new page you have to use document.close().

<body>

<h1>Enter your name below</h1>

<form id="NewPage" onsubmit="CreateNewPage();">
You Name:
<input type="text" id="YourName" /><br />
<input type="submit" value="Submit" />
</form>

<script>
function CreateNewPage() {
	var TheName = document.getElementById("YourName").value;
	document.open();
	document.write("<h2>Welcome!</h2>");
	document.write("Hello "+TheName+" and welcome to my page!");
	document.close();
}
</script>

</body>

In my example I created a form with an input box where the user can type in his name.
The form and the input box are given each an id.
Below I created a submit button which on submit (onsubmit="CreateNewPage();) triggers the JavaScript function CreateNewPage().

Then I created the function CreateNewPage() which grabs the content of the text box
and assigns it to a variable called TheName.

The document.open(); opens the new customized page in the browser.
The two document.write() statements write the text on the page.
The document.close() closes the new page.

The open() and close() methods can be useful when you want to create customized pages on-the-fly based on variables like name, favorite things, etc.

Leave a Reply