ptg16476052
492 LESSON 17: Introducing JavaScript
JavaScript code to events. The JavaScript environment monitors user activity and pro-
vides the opportunity for you to specify that code will be executed when certain events
occur.
There are three ways to bind JavaScript code to an event handler. The first is to use an
HTML attribute. For example, if you want to display an alert when a user clicks a link,
you could bind the event like this:
<a href="/whatever.html" onclick="alert('Be careful')">Link</a>
The disadvantage of this approach is that it makes your JavaScript hard to maintain. You
wind up with JavaScript scattered throughout your documents, and it makes it difficult to
reuse the same JavaScript code on many pages. You should not use this approach for any
but the simplest things.
The second is to bind the event to the appropriate property of the element. If you have a
reference to a link called myLink in JavaScript, you can add a click event like this:
myLink.onclick = function(event) { alert('Be careful'); };
This approach enables you to separate your JavaScript from your HTML, but it allows
you to bind only one function to the click event of the link. This can come back to bite
you in the future or cause problems if you include other JavaScript code on your page
that might also need to bind an event to the click event of that link.
Finally, you can use the addEventListener() method to attach an event handler to an
event on an element. Here’s an example:
myButton.addEventListener('click', function(){ alert('Be careful!'); }, false);
You can use addEventListener() to attach any number of event handlers to the same
event on the same element. It’s the preferred method for event binding currently. If you
need to support older browsers like Internet Explorer 8, there are a number of JavaScript
libraries that will handle the binding of event handlers to events in a safe, cross-platform
way. In the next lesson, you will learn how to use one of the most popular libraries,
jQuery.
Table 17.4 provides a list of the event handlers that JavaScript provides.
TABLE 17.4 JavaScript Event Handlers
Event Handler When It’s Called
onblur Whenever a visitor leaves a specified form field
onchange Whenever a visitor changes the contents of a specified form field
onclick Whenever a visitor clicks a specified element