Reacting to Events
Events are central to JavaScript. Since, the very raison d’etre of JavaScript is to add interactivity to web pages, in fact it would not be wrong to say that events are central to any kind of scripts.
User activity creates events which in turn trigger scripts. Although there are events which are not directly linked to any user activity, such as the load event which is triggered when a web page is being loaded. Events have an event handler which you will have to code. So as and when an event happens, the event handler directs the JavaScript function that, you the web developer, have coded for that particular event.
Browser Wars & Incompatibilities
Although I could tell you about the browser wars that led to many incompatible standards and JavaScript being primarily a web programming language, it is easy to guess the kinds of nightmares a programmer would have had to ensure that his code runs in all major browsers despite their incompatible standards.
Event Handlers – Netscape 2 model
The following code depicts an old outdated way to code an event handler:
<a href="ClicketyClick.html" onclick="alert('Click! Click!')">
Whenever the user clicks on the form, an onclick event is generated, and an alert pops up showing the text “Click! Click”.
Although this certainly does work, but this is not the way to go. The more up-to-date option is to follow the DOM Event specification model.
Browser Compatibility
Because of rising incompatibilities, programmers were forced to write code for specific browsers. An alert reader who has read the earlier chapters, may quickly point out that a if or case structure could easily provide a solution so as to make your code specific to a particular browser, such as the following:
if (Netscape) {
// use Netscape model
}
else if (InternetExplorer) {
// use Microsoft model
}
This approach is at best, a first attempt at arriving at a solution. Browsers like most software, are continuously improved and updated. They have major versions and minor versions. If you follow the above method of writing code, you will have to cater to both major and minor versions of different browsers, which is a hellish job.
Specific Key Questions
Instead of telling you what not to do, let me tell you what to do – ask specific key questions. Questions such as:
- How many categories of events are there and how many events per category are there?
The following events apply to the <body> tag in the the HTML file and are triggered by the window object.
EVENTS related to WINDOW OBJECT
Event | Description |
onafterprintNew | Place your script here to do tasks after a document has been printed |
onbeforeprintNew | Place your script here to do tasks before a document has been printed |
onbeforeunloadNew | Place your script here to do tasks before a document is unloaded |
onerrorNew | Place your event handler here to catch errors |
onhaschangeNew | Place your script here to so that it is executed when the document has undergone change |
onload | Place your script here so that it runs right after the page has loaded |
onmessageNew | Place your script here so that it is fired when a message is triggered |
onofflineNew | Place your scripr here so it runs when the document is not available online |
ononlineNew | Place your script here so that it runs when the documents is available online |
onpagehideNew | Place your script here so that it runs when the window is hidden |
onpageshowNew | Place your script here so that it runs when the window becomes visible |
onpopstateNew | Place your script here so that it runs when the window's history changes |
onredoNew | Place your script here so that it runs when the document performs a redo |
onresizeNew | Place your script here so that it is triggered when the browser window is resized |
onstorageNew | Place your script here so that it runs when a web storage area is updated |
onundoNew | Place your script here so that it runs when the document performs an undo |
onunload | Place your script here so that it runs when |
a page has unloaded. Or if the browser window closes. |
Events related to Form Object
Event | Description |
Onblur | Place your script here so that it is triggered the second in which the element loses focus |
Onchange | Place your script here so that it triggered the second the value of the element is changed |
oncontextmenuNew | Place your script here so that it runs when a context sensitive menu is fired |
Onfocus | Place your script here so that it is triggered the second when the element gets focus |
onformchangeNew | Place your script here so that it runs when a form changes |
onforminputNew | Place your script here so that it runs when a form gets an input from a user |
oninputNew | Place your script here so that it runs when an element gets input from a user |
oninvalidNew | Place your script here so that it runs when an element is invalid |
Onreset | Place your script here so that it is triggered when the Reset button in a form is clicked |
Note: This is unsupported in HTML 5 | |
Onselect | Place your script here so that it is triggered once text has been selected in an element |
Keyboard Events
Event | Description |
Onkeydown | Place your script here so that it is triggered when a user is pressing any key |
Onkeypress | Place your script here so that it is triggered when a user is presses any key |
Onkeyup | Place your script here so that it is triggered when a user is releases a key |
Mouse Events
Events triggered by a mouse, or a pointing device:
Event | Description |
Onclick | Fires on a mouse click on the element |
Ondblclick | Fires on a mouse double-click on the element |
ondragNew | Script to be run when an element is dragged |
ondragendNew | Script to be run at the end of a drag operation |
ondragenterNew | Script to be run when an element has been dragged to a valid drop target |
ondragleaveNew | Script to be run when an element leaves a valid drop target |
ondragoverNew | Script to be run when an element is being dragged over a valid drop target |
ondragstartNew | Script to be run at the start of a drag operation |
ondropNew | Script to be run when dragged element is being dropped |
Onmousedown | Fires when a mouse button is pressed down on an element |
Onmousemove | Fires when the mouse pointer moves over an element |
Onmouseout | Fires when the mouse pointer moves out of an element |
Onmouseover | Fires when the mouse pointer moves over an element |
Onmouseup | Fires when a mouse button is released over an element |
onmousewheelNew | Script to be run when the mouse wheel is being rotated |
onscrollNew | Script to be run when an element's scrollbar is being scrolled |
Image / Audio / Video Events
Event | Description |
Onabort | Script to be run on abort |
oncanplayNew | Script to be run when a file is ready to start playing (when it has buffered enough to begin) |
oncanplaythroughNew | Script to be run when a file can be played all the way to the end without pausing for buffering |
ondurationchangeNew | Script to be run when the length of the media changes |
onemptiedNew | Script to be run when something bad happens and the file is suddenly unavailable (like unexpectedly disconnects) |
onendedNew | Script to be run when the media has reach the end (a useful event for messages like "thanks for listening") |
onerrorNew | Script to be run when an error occurs when the file is being loaded |
onloadeddataNew | Script to be run when media data is loaded |
onloadedmetadataNew | Script to be run when meta data (like dimensions and duration) are loaded |
onloadstartNew | Script to be run just as the file begins to load before anything is actually loaded |
onpauseNew | Script to be run when the media is paused either by the user or programmatically |
onplayNew | Script to be run when the media is ready to start playing |
onplayingNew | Script to be run when the media actually has started playing |
onprogressNew | Script to be run when the browser is in the process of getting the media data |
onratechangeNew | Script to be run each time the playback rate changes (like when a user switches to a slow motion or fast forward mode) |
onreadystatechangeNew | Script to be run each time the ready state changes (the ready state tracks the state of the media data) |
onseekedNew | Script to be run when the seeking attribute is set to false indicating that seeking has ended |
onseekingNew | Script to be run when the seeking attribute is set to true indicating that seeking is active |
onstalledNew | Script to be run when the browser is unable to fetch the media data for whatever reason |
onsuspendNew | Script to be run when fetching the media data is stopped before it is completely loaded for whatever reason |
ontimeupdateNew | Script to be run when the playing position has changed (like when the user fast forwards to a different point in the media) |
onvolumechangeNew | Script to be run each time the volume is changed which (includes setting the volume to "mute") |
onwaitingNew | Script to be run when the media has paused but is expected to resume (like when the media pauses to buffer more data) |
- What do I do so that the default action in an event is not triggered?
There’s a technique that was standard since the time of Netscape2 and you can still use it. If your event handling script returns a false, the default action is prevented.
- How to register an event handler to an HTML element?
You can do in four different way: inline, traditional, W3C and Microsoft.
- Having accessed an event, how do I get to its properties?”
This is a compatibility minefield, an event property compatibility table will come in handy. You will also need a very strict object detection.
What you will have to remember when writing code that runs on multiple browsers is to not use a generic approach, otherwise you will face hell when you are trying to access properties of events. The smart way is to select an event that can be accessed by all, then when you try to read out the event properties it isn’t such an issue.
Scripting an Event Handler
The first step towards coding your own event handler is to register an event handler. You do this by ensuring that your script is fired every single time by the browser when this event takes place. As mentioned earlier, in such a scenario, you are on a crossroad. You can either use, inline, tradition, W3C or the Microsoft approach. Lets leave the fancy stuff and stick to the traditional method so as to ensure 100% compatibility with other browsers.
Here’s how you register an event handler, in the traditional way:
element.onclick = MyCode;
if (element.captureEvents) element.captureEvents(Event.CLICK);
MyCode() refers to your event handling function. Mycode is registered as the event handler of the click event of HTML’s element. This will translate to as and when a user clicks on that element, your function MyCode will get executed.
Get access to the Event
Having registered your own event handler, the next thing you would want, is to get a handle on the actual event. Here’s some code for you to munch through:
function MyCode(k) {
if (!k) var k = window.event // k refers to the event
}
You can access the variable k in all browsers. This variable ‘k’ refers to the event.
The Element
If you want to have access to the HTML element on which the event took place, you can either use the ‘this’ keyword or use the property – target / srcElement.
Here is how you would use the keyword ‘this’ to have access to the HTML element. Note, that using the keyword ‘this’ will not guarantee you access of the HTML element. But if you use it in combination with the traditional approach, it works just fine.
function MyCode(k) {
if (!k) var k = window.event // k refers to the event
// this refers to the HTML element which currently handles the event
// target/srcElement refer to the HTML element the event originally took place on
}
Reading Event Properties
Reading event properties is again a compatibility minefield. Your map to the mine field is to use a very detailed object mechanism, by first checking if each property exists, based on which, you can try reading out its value.
Consider this:
function MyCode(k) {
if (!k) var k = window.event
if (k.keyCode) code = k.keyCode;
else if (k.which) code = k.which;
}
The variable ‘code’ will now contain the key that has been pressed irrespective of which browser is being used.
And with this, we are now done with events and elements and hopefully you have got a good grasp of both concepts. Let us move on to better understanding objects. A short word before you move on, whenever you are coding make it very logical and keep commenting your code, that way you will never lose yourself in your own logic.