Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

Events 491

17


The JavaScript Environment


I’ve taken you on a very brief tour of the JavaScript language, but beyond the basic lan-
guage syntax, which involves declarations, control structures, data types, and even core
objects that are part of the JavaScript language, there’s also the browser environment.
When your scripts run, they have access to the contents of the current page, to other
pages that are open, and even to the browser itself. I’ve mentioned the document object,
which provides access to the contents of the current page.


Now let’s look at a specific object. The top-level object in the browser environment is
called window. The window object ’s children provide information about the various ele-
ments of a web page. Here are some of the most commonly used children of window:


location Contains information about the location of the current web document,
including the URL and components of the URL, such as the protocol,
domain name, path, and port.
history Holds a list of all the sites that a web browser has visited during the cur-
rent session and gives you access to built-in functions that enable you to
send the user forward or back within the history.
document Contains the complete details of the current web page. All the tags and
content on the page are included in a hierarchy under document. Not only
can you examine the contents of the page by way of the document object,
but you can also manipulate the page’s content s, too.

You can find a complete list of the available objects in the Mozilla JavaScript documen-
tation at https://developer.mozilla.org/en-US/docs/Web/JavaScript.


Because the entire browser environment is accessible through this hierarchical set of
objects, you can access anything as long as you know where it lives in the hierarchy. For
example, all the links on the current page are stored in the property document.links,
which contains an array. Each of the elements in the array has its own properties as
well, so to get the location to which the first link in the document points, you use
document.links[0].href.


Events


All the examples you’ve seen so far are executed as soon as the page loads. JavaScript
is about making your pages more interactive, which means writing scripts that function
based on user input and user activity. To add this interactivity, you need to bind your

Free download pdf