Resig 06 A
Resig 06 A
Listing 1-4. Using the Document Object Model to Locate and Manipulate Different
DOM Elements
<html>
<head>
<title>Introduction to the DOM</title>
<script>
// We can't manipulate the DOM until the document
// is fully loaded
window.onload = function(){
};
</script>
</head>
<body>
<h1>Introduction to the DOM</h1>
<p class="test">There are a number of reasons why the
DOM is awesome, here are some:</p>
7273ch01final.qxd 11/16/06 8:23 AM Page 9
<ul>
<li id="everywhere">It can be found everywhere.</li>
<li class="test">It's easy to use.</li>
<li class="test">It can help you to find what you want, really quickly.</li>
</ul>
</body>
</html>
The DOM is the first step to developing unobtrusive JavaScript code. By being able to
quickly and simply navigate an HTML document, all resulting JavaScript/HTML interactions
become that much simpler.
Events
Events are the glue that holds together all user interaction within an application. In a nicely
designed JavaScript application, you’re going to have your data source and its visual repre-
sentation (inside of the HTML DOM). In order to synchronize these two aspects, you’re
going to have to look for user interactions and attempt to update the user interface accord-
ingly. The combination of using the DOM and JavaScript events is the fundamental union
that makes all modern web applications what they are.
All modern browsers provide a number of events that are fired whenever certain inter-
actions occur, such as the user moving the mouse, striking the keyboard, or exiting the page.
Using these events, you can register code that will be executed whenever the event occurs.
An example of this interaction is shown in Listing 1-5, where the background color of the
<li>s change whenever the user moves his mouse over them.
Listing 1-5. Using the DOM and Events to Provide Some Visual Effects
<html>
<head>
<title>Introduction to the DOM</title>
<script>
// We can't manipulate the DOM until the document
// is fully loaded
window.onload = function(){
// Find all the <li> elements, to attach the event handlers to them
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {