Java Reference
In-Depth Information
• The code for the event handlers is hidden away in the markup, making it difficult
to find where these events have been placed.
• The JavaScript code has to be entered in a string, so you need to be careful when
using apostrophes and quote marks.
I've included them here because you may see them in some code examples.
Older Event Handlers
Another method is to use the event handler properties that all node objects have. These
can be assigned to a function that would be invoked when the event occurred. The follow-
ing example would trigger an alert:
document.onclick = function (){ console.log("You
clicked!"); }
This method is an improvement on the inline event handlers as it keeps the JavaScript out
of the HTML markup. It is also well-supported and will work in all browsers, including
older versions. Unfortunately, it still has the restriction that only one function can be used
for each event.
Event Listeners
The recommended standard way of dealing with events is to use event listeners . These were
outlined in DOM level 2 and allow multiple functions to be attached independently to dif-
ferent events. They are supported in all modern browsers, although only in Internet Ex-
plorer from version 9 onwards.
The addEventListener() method is called on a node object, the node to which the
event listener is being applied. For example, this code will attach an event listener to the
document's body:
document.body.addEventListener("click",doSomething);
The addEventListener() method can also be called without a node, in which case it
is applied to the global object, usually the whole browser window.
 
Search WWH ::




Custom Search