HTML and CSS Reference
In-Depth Information
alert(“Boo!");
});
}
4.
Save the
example10-6.js
file.
5.
Now create a new HTML file called
example10-6.html
.
6.
Copy the following HTML code into this file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Event Listeners</title>
</head>
<body>
<button id="btn">Click me!</button>
<script src="example10-6.js"></script>
</body>
</html>
7.
Save this file.
Now open up the
example10-6.html
file in your web browser. If you click the button you should be confronted
by an alert dialog that contains the text
Boo!
Making Decisions
When writing programs, you will meet scenarios in which you need to make a decision before executing code.
Maybe you want to check that the user has provided valid data, or that a number is within a certain range. You can
make these decisions in your code using
if
and
else
statements.
An
if
statement should contain a condition that evaluates to either
true
or
false
. If the condition evaluates to
true
, the code within the block is executed; if it is
false
, the code is skipped. Here is an example of a simple
if
statement:
if(a < b) {
document.write(“a is smaller than b!");
}
In this example, the condition would evaluate to
true
if the value of the
a
variable is smaller than the value of the
b
variable. This means that the code would execute and the text would be output to the screen.
You can find a comprehensive list of JavaScript operators that can be used in conditions at