You now know how to attach the various different event handlers to the various objects within your web page. Sometimes you will have multiple objects on the page where you want to attach the same event handler to run the same code.
This is easily done for two or three objects on your page but what do you do if you want an event handler attached to all of the objects on your page? If we create a global event handler then we can intercept all occurrences of one or more specified events throughout the entire web page without having to attach that event handler to any of the objects on our page.
The Global Handler
Let's start by looking at an example of a global event handler. The following code runs the kH() function whenever an onkeypress event occurs anywhere on your page. That function strips out any enter key presses so that your page effectively ignores the enter key.
var pK = e? e.which: window.event.keyCode;
return pK != 13;
}
document.onkeypress = kH;
if (document.layers)
document.captureEvents(Event.KEYPRESS);
The third last line of this code are what does most of the work of converting onkeypress (in this example) into a global handler. The first of these two lines identifies the event handler that we want to make global (onkeypress) and the function that we want to run when this event occurs (kH). The last two lines are specific to Netscape 4 which requires this extra code in order to capture the event and can be left off if you do not need to support that browser.
If you want to make more than one event handler operate globally you would replicate the third last line specifying the event handler and the function that it is to call. If you need to support Netscape 4 then you would also add the event into the end of the last line.
document.onclick = mD;
if (document.layers)
document.captureEvents(Event.KEYPRESS || Event.CLICK);
How the information associated with the event gets passed to the function (which key was pressed in our example) depends on which browser is being used. The example code tests for which browser is used as the first statement within the function in order to retrieve the ascii value of the key that was pressed from whichever of the two locations that the browser may have stored it in.
Using What You Know
You can now take any event handler that you have attached to a single object on any of your web pages and change it so that it can be triggered when the appropriate event occurs anywhere on your web page.