Chapter 6

  1. The three approaches are inline, using syntax such as onload on the body element; using the traditional DOM Level 0 event capturing, such as window.onload; and using the newer DOM Level 2 events, such as addEventListener or attachEvent.

  2. 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 or screenY properties.

  3. 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 the cancelBubble property to true.

  4. The answer is:

  5. if (window.addEventListener) {
          window.addEventListener("load",functionCall,false);
       } else if (window.attachEvent) {
          window.attachEvent("onload", functionCall);
       }
  6. Though we haven’t covered capturing keyboard events, typically you capture the keydown event and then access the Unicode key code from the which property on the event:

  7. 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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.