HTML and CSS Reference
In-Depth Information
If all goes to plan, this will output the following on your screen:
Hello Joe
Let's write a little program that makes use of the sayHello() function. Here you are going to write out a hello
message to four different people.
1. Create a new file in your text editor called example10-5.js .
2. Copy the following code into this new file:
window.onload = function() {
sayHello('Joe');
sayHello('Beth');
sayHello('Steve');
sayHello('James');
};
// Print out a hello message.
function sayHello(name) {
document.write('Hello ' + name + '<br>');
}
3. Save the example10-5.js file.
4. Create a new example10-5.html file.
5. Copy the following HTML into this file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Say Hello</title>
</head>
<body>
<script src="example10-5.js"></script>
</body>
</html>
6. Save the example10-5.html file.
Open the example10-5.html file in your browser. You should see the following output on the screen:
Hello Joe
Hello Beth
Hello Steve
Hello James
In this example, you used the sayHello() function that you created to output a hello message to Joe and his
friends.
Functions are extremely useful for creating maintainable code. Try to create functions whenever you can; they will
make your life much easier as your programs grow.
Search WWH ::




Custom Search