HTML and CSS Reference
In-Depth Information
2. Copy the following code into this new file.
window.onload = function() {
var name = prompt('Your name please');
document.write('Hello ' + name + '!');
3. Save the example10-3.js file.
4. Create a new example10-3.html file in your text editor.
5. Copy the following code into this HTML file.
<!DOCTYPE html>
<meta charset="utf-8">
<title>Say Hello</title>
<script src="example10-3.js"></script>
6. Save the example10-3.html file.
Now view the example10-3.html file in your browser. You should be prompted for your name. Type this into
the text box and click OK (or press Enter). A hello message should display on the screen.
This small program addresses a number of different concepts from JavaScript. First, you declared a variable ( name )
to hold some data (more on variables soon), and then you told the browser to prompt the user for her name, passing
in some text to be displayed in the pop-up window. You then combined the name that you collected with some other
text and printed it all out to the screen.
This may seem like a fairly useless little program, but here you have covered the key programming concept of input
and output. Next up: taking a closer look at variables.
Variables are used to store pieces of data so that you can play around with them in your program. Declaring a vari-
able in JavaScript is easy; unlike some other programming languages, you do not need to specify what type of data
the variable will hold (for example, a number or text). Programming languages like JavaScript are referred to as dy-
namically typed languages.
To declare a variable, you start by using the JavaScript keyword var . This tells the browser that you are creating a
new variable. You then add the name of your variable. Variable names should not contain spaces, and you should use
camel-case to join multiple words together. For example, “guitar stand” becomes guitarStand . Note the capital
letter of the second word: That's where camel-case gets its name—like the hump on a camel's back.
Once you have declared the name of your variable, you can assign it an initial value. This is known as initializing a
variable. To do this, you use the equal sign (=) followed by your data. The statement below shows a variable
leafColor that is initialized with the value green .
var leafColor = “green";
Search WWH ::

Custom Search