Chapter 6
The three approaches are inline, using syntax such as
onload
on thebody
element; using the traditional DOM Level 0 event capturing, such aswindow.onload
; and using the newer DOM Level 2 events, such asaddEventListener
orattachEvent
.If using the DOM Level 0 event-handling system, you either access the event object on the window object or passed in as a function. For DOM Level 2, the event object is always passed into the function. From the event object, access the
screenX
orscreenY
properties.The IE approach differs from that supported by most browsers, and as such, you have to support both it and the others. Test if the
stopPropagation
method is supported on the event object and if so, invoke it; otherwise, set thecancelBubble
property totrue
.The answer is:
if (window.addEventListener) { window.addEventListener("load",functionCall,false); } else if (window.attachEvent) { window.attachEvent("onload", functionCall); }
Though we havenâÂÂt covered capturing keyboard events, typically you capture the
keydown
event and then access the Unicode key code from thewhich
property on the event:if (document.addEventListener) { document.addEventListener("keydown",getKey,true); } else if (document.attachEvent) { document.attachEvent("onkeydown", getKey); } function getKey(evnt) { alert(evnt.which); }
Get Learning JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.