HomeJavaScript Page 2 - Understanding The JavaScript Event Model (part 1)
Popeye() And Olive() - JavaScript
This may be news to you, but JavaScript comes with a powerfuland flexible event model, one which provides developers with astandardized way of trapping and handling client-side events likekeystrokes and mouse clicks. This two-part article takes an in-depthlook at how this event model works, demonstrating some practical (andnot-so-practical) uses of the most common event handlers.
Simply put, the event model provides a way for a user to interact with JavaScript. It consists of two basic components, events and event handlers, which together define what happens when the user performs a particular action.
An event may be defined, very simply, as an action performed on a Web page - for example, clicking a button, moving the mouse pointer over a hyperlink and so on. Events are not necessarily generated by the user; they may be generated automatically by a piece of code as well.
An event handler, as the name suggests, handles an event - it defines the action to be taken by a script when a particular event (or type of event) occurs. Event handlers exist for most of the common events that are generated on a Web page, including mouse movement, mouse clicks, keyboard activity and page loads.
Here's a quick example that might make this theory a little clearer:
<body onLoad="thisFunction()">
...
</body>
If you were to translate the line of code above into English, it would read, "invoke the JavaScript function thisFunction() when the page loads". The event handler in this case is the onLoad handler, which can be used to perform specific actions when a Web page loads into the browser.
Another example, and one you've probably seen before, is
Or, in English, "call the JavaScript function popeye() when the mouse pointer moves over this hyperlink, and the JavaScript function olive() when the pointer moves away from this hyperlink". These event handlers are most commonly used for image swaps...as you'll see very shortly.