09 - Events in Javascript

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

EventDescription
onafterprintNewPlace 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
onbeforeunloadNewPlace your script here to do tasks before a document is unloaded
onerrorNew Place your event handler here to catch errors
onhaschangeNewPlace your script here to so that it is executed when the document has undergone change
onloadPlace your script here so that it runs right after the page has loaded
onmessageNewPlace your script here so that it is fired when a message is triggered
onofflineNewPlace your scripr here so it runs when the document is not available online
ononlineNewPlace your script here so that it runs when the documents is available online
onpagehideNewPlace your script here so that it runs when the window is hidden
onpageshowNewPlace your script here so that it runs when the window becomes visible
onpopstateNewPlace your script here so that it runs when the window's history changes
onredoNewPlace your script here so that it runs when the document performs a redo
onresizeNewPlace your script here so that it is triggered when the browser window is resized
onstorageNewPlace your script here so that it runs when a web storage area is updated
onundoNewPlace your script here so that it runs when the document performs an undo
onunloadPlace your script here so that it runs when
a page has unloaded. Or if the browser window closes.

Events related to Form Object

EventDescription
OnblurPlace your script here so that it is triggered the second in which the element loses focus
OnchangePlace your script here so that it triggered the second the value of the element is changed
oncontextmenuNewPlace your script here so that it runs when a context sensitive menu is fired
OnfocusPlace your script here so that it is triggered the second when the element gets focus
onformchangeNewPlace your script here so that it runs when a form changes
onforminputNewPlace your script here so that it runs when a form gets an input from a user
oninputNewPlace your script here so that it runs when an element gets input from a user
oninvalidNewPlace your script here so that it runs when an element is invalid
OnresetPlace your script here so that it is triggered when the Reset button in a form is clicked
Note: This is unsupported in HTML 5
OnselectPlace your script here so that it is triggered once text has been selected in an element

Keyboard Events

 

EventDescription
OnkeydownPlace your script here so that it is triggered when a user is pressing any key
OnkeypressPlace your script here so that it is triggered when a user is presses any key
OnkeyupPlace 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:

EventDescription
OnclickFires on a mouse click on the element
OndblclickFires on a mouse double-click on the element
ondragNewScript to be run when an element is dragged
ondragendNewScript to be run at the end of a drag operation
ondragenterNewScript to be run when an element has been dragged to a valid drop target
ondragleaveNewScript to be run when an element leaves a valid drop target
ondragoverNewScript to be run when an element is being dragged over a valid drop target
ondragstartNewScript to be run at the start of a drag operation
ondropNewScript to be run when dragged element is being dropped
OnmousedownFires when a mouse button is pressed down on an element
OnmousemoveFires when the mouse pointer moves over an element
OnmouseoutFires when the mouse pointer moves out of an element
OnmouseoverFires when the mouse pointer moves over an element
OnmouseupFires when a mouse button is released over an element
onmousewheelNewScript to be run when the mouse wheel is being rotated
onscrollNewScript to be run when an element's scrollbar is being scrolled

Image / Audio / Video Events

EventDescription
OnabortScript to be run on abort
oncanplayNewScript to be run when a file is ready to start playing (when it has buffered enough to begin)
oncanplaythroughNewScript to be run when a file can be played all the way to the end without pausing for buffering
ondurationchangeNewScript to be run when the length of the media changes
onemptiedNewScript to be run when something bad happens and the file is suddenly unavailable (like unexpectedly disconnects)
onendedNewScript 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
onloadeddataNewScript to be run when media data is loaded
onloadedmetadataNewScript to be run when meta data (like dimensions and duration) are loaded
onloadstartNewScript to be run just as the file begins to load before anything is actually loaded
onpauseNewScript to be run when the media is paused either by the user or programmatically
onplayNewScript to be run when the media is ready to start playing
onplayingNewScript to be run when the media actually has started playing
onprogressNewScript to be run when the browser is in the process of getting the media data
onratechangeNewScript to be run each time the playback rate changes (like when a user switches to a slow motion or fast forward mode)
onreadystatechangeNewScript to be run each time the ready state changes (the ready state tracks the state of the media data)
onseekedNewScript to be run when the seeking attribute is set to false indicating that seeking has ended
onseekingNewScript to be run when the seeking attribute is set to true indicating that seeking is active
onstalledNewScript to be run when the browser is unable to fetch the media data for whatever reason
onsuspendNewScript to be run when fetching the media data is stopped before it is completely loaded for whatever reason
ontimeupdateNewScript to be run when the playing position has changed (like when the user fast forwards to a different point in the media)
onvolumechangeNewScript to be run each time the volume is changed which (includes setting the volume to "mute")
onwaitingNewScript 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.

Like us on Facebook