One really useful document method is write. We'll take a look at that now.
The document's write method can be used to insert text onto your web page (this text can actually be HTML elements). Try this as an example:
- Create a new HTML web page from your template
- Save it with the name write_method.html
- Add the following H1 heading to the HTML: <H1>The document.write method</H1>
- Put two SCRIPT tags in the BODY section of the HTML
- Between the two SCRIPT tags, add the following:
document.write( window.screen.height );
(Notice the semicolon at the end of the line. We'll use them to separate each line of code from now on.)
Save your work and open up the web page in a browser. You should see this:
Instead of an alert box, we're now writing the screen height directly to the web page. (Your screen height may well be different.)
document.write("Screen Height=" + window.screen.height);
What we've done here is something concatenation. This just means joining strings of text together. We've added some direct text between quotation marks. After a plus symbol ( + ) we then have the screen height code. The plus symbol when used like this means "join together". You can use it as many times as you want. For example:
document.write("SH=" + window.screen.height + " SW=" + window.screen.width);
The SH and SW above obviously mean Screen Height and Screen Width. But note where all the plus symbols, commas and spaces are. Get your plus symbols and/or commas wrong and your code won't work.
You can use HTML tags with concatenation. For example, if you want to spread things over two lines, you can use the BR tag. Like this:
document.write("SH=" + window.screen.height + "<BR>" + "SW=" + window.screen.width);
The BR tag is surrounded by quotation marks. You need the quote marks for any HTML that you insert using the write method.
You can use document.write as many times as you want. In the code below, we have moved the SCRIPT tags back to the HEAD section. We then used document.write twice: once to add the H1 line, and once to add the text below it.
Try these two exercises to get the hang of document.write.
Use concatenation with document.write to create the following in your browser:
We used document.write twice here. The first one wrote a H1 heading. The second one combined the text "Your browser is set to:" with window.navigator.language. We also have bold text for the browser language (your language may be different - it depends where you are in the world). Of course, you'll need to know what the HTML tag for bold text is!
Use document.write to create an address like the one below:
This address is centre aligned in the browser, with the first line in bold. We used document.write seven times. Five of those seven times are for the address. The other two are used to get the centre alignment. So you start with:
And the last line is:
What this does is to get you a paragraph with the alignment. The other five uses of document.write are for inside of these two.