Changing the HTML with JavaScript
JavaScript can write HTML into the body of the web page and this gives us a great
deal of power and flexibility.
Type this page into NotePad++
<html>
<!-- Changing the web page -->
<head>
<title>My third program</title>
</head>
<body>
<script>
// Get the user's name and say hello.
userName = prompt("What is your name", "")
document.write("Hello " + userName + ".")
</script>
This text will appear after the welcome message.
</body>
</html>
Save this page and open it in FireFox.
You should see a box on screen asking for your name as before.
Enter your name and you should see the welcome message displayed on the
web page itself rather than in an alert.
Object orientation
The new feature here is our first sight of a feature called object orientation within
JavaScript. There will be more details later in this tutorial but all we need to know
for the moment is that an object represents something in the program. Something
which has its own built-in facilities which can do the things which this object needs
to be able to do.
In this example, document is the "something" and it's a predefined object which
refers to the web page itself. One of the facilities of the page is to add to its own
HTML content. These facilities are known as methods and the document.write
method is telling the document object to take the text it's been given as a parameter
and insert it into the body of the HTML document.
Formatting the output
The two pieces of text will appear on the same line of the web page because the browser
hasn't been told to start a new line. We're producing HTML with our JavaScript here so we
can use the familiar technique of <p> tags. All we have to do is add the paragraph
tags to the text we want to appear on the page:
document.write("<p>Hello " + userName + ".</p>")
Note that the tags are inside the quotes. The HTML of the web page is plain text
and we are using document.write to produce this text.
Punctuation
You will I fear make mistakes here. It's very easy to get the sequence of characters
wrong at the end of the line. Working from the outside in we have:
-
a regular bracket to mark the end of the output from document.write.
-
a double quote to mark the end of the string literal.
-
an angle bracket to mark the end of the tag.
All very straightforward if you look at it slowly. It would be really useful if
NotePad++ would do its trick of matching the brackets here but NotePad++ doesn't
know that we're trying to write HTML inside our JavaScript program. It just sees it
as text.
|