HTML and CSS Reference
In-Depth Information
Assignment event handling
Assigning the event function to the event property through JavaScript is another way to set
up event handlers. This method has been around for a long time and is still widely used. For
the preceding example of the onload event, the following changes are required to reflect
assigning an event handler through JavaScript:
<html>
<head>
<script>
window.onload = onloadHandler();
function onloadHandler() {
alert("hello event.");
}
</script>
</head>
<body >
...
</body>
</html>
In this code, the HTML element for the body is cleaned up and the onload event is as-
signed in JavaScript. The window object isn't the same as the body element, but it demon-
strates the concept of assigning code that needs to run as soon as the page is loaded. Notice
that the assignment of the onloadHandler is in the script block but not inside any function.
For this to succeed, the window object must exist. Since the window object is a global object
it will exist. However, to access elements of the page, the page must be loaded or the script
must run after the renderer processes the HTML. For example, if the page has a canvas and
the functionality to enable users to draw on it with a mouse, the event handlers for the mouse
activities would have to be assigned either at the bottom of the page or within the window's
onload event. The onload event is triggered when the entire page is loaded, so it's possible to
get a reference to the page elements and hook up the event handlers.
A more common way to do this is to assign an anonymous function to the window's
onload event and hook up all the necessary events. The concept of an anonymous function is
discussed shortly. It's used throughout the topic as shown here:
window.onload = function () {
//do event setup in here.
}
Using the addEventListener and removeEventListener methods
addEventListener and removeEventListener are the two preferred methods to hook up a func-
tion to an event and then to remove it later as needed. The addEventListener method accepts
two required parameters and one optional parameter:
addEventListener(< event name >,< event function >,< optional cascade rule >)
 
Search WWH ::




Custom Search