HTML and CSS Reference
In-Depth Information
The event name is the name of the event to be handled. The event name will be as you've
seen in the previous examples except without the on prefix. For example, the name of the
onload event is just load . The event function is the one that should run when the event occurs,
the listener. The optional cascade rule provides some flexibility in how the events move through
nested DOM elements. This is examined in more detail later in the discussion on event bub-
The removeEventListener takes exactly the same parameters. What this implies is that more
than one event listener can be added for the same event and then removed. Thinking in the
context of a complicated program such as a game, you might need to turn on and off specific
event handlers for the same event. Consider the following example:
window.addEventListener("load", onloadHandler, false);
window.addEventListener("load", onloadHandler2, false);
window.addEventListener("load", onloadHandler3, false);
function onloadHandler() {
alert("hello event 1.");
function onloadHandler2() {
alert("hello event 2.");
function onloadHandler3() {
alert("hello event 3.");
Each event fires in the order in which it was added when the window is finished loading. To
remove the onloadHandler2 event, all that's needed is a call to the removeEventListener :
window.removeEventListener("load", onloadHandler2, false);
When handling DOM events, the custom events you create are not a replacement for the
built-in functionality provided by the DOM element. The handling of the event allows you to
do some custom logic or manipulation, but when event handling is complete, the processing
returns back to the JavaScript API, which processes its own implementation for the event. If
this isn't desirable, you can stop the event processing.
Using anonymous functions
In the examples so far, event handlers have been assigned via named functions. The advan-
tage to using named functions is that you can later remove event listeners as needed. You
can't identify anonymous functions after they are assigned as event listeners to manipulate
them. In the example in the preceding section, three event listeners were added to the same
event, and then one event was removed. This was possible only because the name of the
event listener function was known.
Search WWH ::

Custom Search