Documente Academic
Documente Profesional
Documente Cultură
</script>
The other children of the window object visible are the location object (containing details of the
URL of the currently loaded page), the history object (containing details of the browser’s
previously visited pages), and the navigator object (which stores details of the browser type,
version, and capabilities).
Even if you don’t realize it, you’ve seen the results of the window object’s alert method on many
occasions. The window object, you’ll recall, is at the top of the DOM hierarchy and represents
the browser window that’s displaying your page. When you call the alert() method, the browser
pops open a dialog displaying your message, along with an OK button.
<script>window.alert("Here is my message");</script>
document.write()
You can probably guess what the write method of the document object does, simply from its
name. This method, instead of popping up a dialog, writes characters directly into the DOM of
the document.
</script>
A second, and usually preferable, way to include your code is to save your JavaScript into a
separate file and use the <script> element to include that file by name using the src (source)
attribute:
<script src='mycode.js'></script>
The preceding example includes the file mycode.js, which contains the JavaScript statements. If
your JavaScript file is not in the same folder as the calling script, you can also add a (relative or
absolute) path to it:
<script src='/path/to/mycode.js'></script>
or
<script src='http://www.example.com/path/to/mycode.js'></script>
Placing your JavaScript code in a separate file offers some important advantages:
When the JavaScript code is updated, the updates are immediately available to any page using
that same JavaScript file. This capability is particularly important in the context of JavaScript
libraries, which we look at in a later lesson.
The code for the HTML page is kept cleaner and therefore is easier to read and maintain.
Performance is slightly improved because your browser caches the included file, therefore
storing a local copy in memory until the next time it is needed by this or another page.
File Extensions
It is customary to give files of JavaScript code the file extension .js, as in this example. However,
your included code files can have any extension, and the browser will try to interpret the contents
as JavaScript
this is statement 2
Alternatively, they can be combined in the same line by terminating each with a semicolon:
this is statement 1; this is statement 2;
To ease the readability of your code and to help prevent hard-to-find syntax errors, it’s good
practice to combine both methods by giving each statement its own line and terminating the
statement with a semicolon too:
this is statement 1;
this is statement 2;
Note
Comment Syntax
JavaScript can also use the HTML comment syntax for single-line comments:
<!-- this is a comment -->
A more convenient way of entering multiline comments to your code is to prefix your comment
with /* and terminate it with */. A comment written using this syntax can span multiple lines:
/* This comment can span
Adding comments to your code is really a good thing to do, especially when you’re writing
larger or more complex JavaScript applications. Comments can act as reminders to you, and also
as instructions and explanations to anybody else reading your code at a later date.
USING VARIABLES
You can think of a variable as a named “pigeon-hole” where you keep a particular piece of data.
Such data can take many different forms—an integer or decimal number, a string of characters,
or various other data types discussed later in this lesson or in those that follow. You can call
variables pretty much anything you want, so long as you use only alphanumeric characters, the
dollar sign ($), or underscores in the name.
Note
Case Sensitivity
JavaScript is case sensitive; a variable called mypetcat is a different variable
from Mypetcat or MYPETCAT.
gning a Value and Testing Equality
It’s important to note that the = character is used only for assigning a value. When you need to
instead test whether two values or expressions are equal, it’s incorrect to use just the = character.
Instead, you need == to test equality:
Arithmetic Operations
First, JavaScript allows you to carry out operations using the standard arithmetic operators of
addition, subtraction, multiplication, and division:
var theSum = 4 + 3;
As you’ve surely guessed, after this statement is executed, the variable theSum will contain a
value of 7. You can use variable names in operations too:
var productCount = 2;
You can use JavaScript to subtract (–), multiply (*), and divide (/) in a similar manner:
subtotal = total – shipping;
To calculate the remainder from a division, you can use JavaScript’s modulus division operator.
It is denoted by the % character:
In this example, the variable itemsInLastBox would contain the number 4 after the last statement
completes.
JavaScript also has convenient operators to increment (++) or decrement (--) the value of a
variable:
productCount++;
Similarly,
items--;
Tip
Combining Operators
If you need to increment or decrement a variable by a value other than one, JavaScript also
allows you to combine other arithmetic operators with the = operator—for example, += and -=.
The following two lines of code are equivalent:
total = total + 5;
total += 5;
counter -= step;
You can use this notation for other arithmetic operators such as multiplication and division too:
price = price * uplift;
price *= uplift;
Operator Precedence
When you use several operators in the same calculation, JavaScript uses precedence rules to
determine in what order the calculation should be done. For example, consider the statement
var average = a + b + c / 3;
If, as the variable’s name implies, you’re trying to calculate an average, this would not give the
desired result; the division operation would be carried out on c before adding the values
of a and b to the result. To calculate the average correctly, you would have to add parentheses to
the statement, like this:
var average = (a + b + c) / 3;
If you have doubts about the precedence rules, I recommend that you always use parentheses
liberally. There is no cost to doing so, it makes your code easier to read (both for you and for
anyone else who later has to edit or decipher it), and it ensures that precedence issues don’t spoil
your calculations.
Note
Precedence Rules
If you have programming experience in another language such as PHP or Java, you’ll find that
the precedence rules in JavaScript are pretty much identical to the ones you’re used to.
Using the + Operator with Strings
Arithmetic operators don’t make much sense if the variables they operate on contain strings
rather than numeric values. The exception is the + operator, which JavaScript interprets as an
instruction to concatenate (join together sequentially) two or more strings:
If you try to use the + operator on two variables, one of which is a string and the other numeric,
JavaScript converts the numeric value to a string and concatenates the two:
var name = "David";
alert(name + age);
Note
Adding Event Handlers to HTML Elements
While adding event handlers directly into HTML elements is perfectly valid, doing so is not
regarded these days as good programming practice. This approach serves us well for the
examples in Part I of this book, but later in the book you’ll learn more powerful and elegant
ways to use event handlers.
Let’s look at the example in Listing 2.3.
<!DOCTYPE html>
<html>
<head>
<title>onClick Demo</title>
</head>
<body>
<input type="button" onclick="alert('You clicked the button!')" value="Click Me" />
</body>
</html>
The HTML code adds a button to the <body> element of the page and supplies that button with
an onclick attribute. The value given to the onclick attribute is the JavaScript code you want to
run when the HTML element (in this case a button) is clicked. When the user clicks on the
button, the onclick event is activated (we normally say the event has been “fired”) and the
JavaScript statements listed in the value of the attribute are executed.
In this case, there’s just one statement:
alert('You clicked the button!')
onMouseOver and onMouseOut Event Handlers
When you simply want to detect where the mouse pointer is on the screen with reference to a
particular page element, onMouseOver and onMouseOut can help to do that.
The onMouseOver event is fired when the user’s mouse cursor enters the region of the screen
occupied by the element in question. The onMouseOut event, as you’ve already probably
guessed, is fired when the cursor leaves that same region.
This provides a simple example of the onMouseOver event in action.
<!DOCTYPE html>
<html>
<head>
<title>onMouseOver Demo</title>
</head>
<body>
<img src="image1.png" alt="image 1" onmouseover="alert('You entered the image!')" />
</body>
</html>
Replacing onmouseover with onmouseout in the code will, of course, simply fire the event
handler—and therefore pop up the alert dialog—as the mouse leaves the image, rather than doing
so as it enters.