Obtaining the event object

  1. W3C way
  2. Internet Explorer way
  3. Cross-browser solution
    1. The inline variant
  4. Summary

The event object is always passed to the handler and contains a lot of useful information what has happened.

One property is generic:

  • event.type - type of the event, like “click”

Different types of events provide different properties. For example, the onclick event object contains:

  • event.target - the reference to clicked element. IE uses event.srcElement instead.
  • event.clientX / event.clientY - coordinates of the pointer at the moment of click.
  • … Information about which button was clicked and other properties. We’ll cover them in details later.

Now our aim is to get the event object. There are two ways.

W3C way

Browsers which follow W3C standards always pass the event object as the first argument for the handler.

For instance:

element.onclick = function(event) {
 // process data from event
}

It is also possible to use a named function:

function doSomething(event) {
  // we've got the event
}

element.onclick = doSomething

It is possible to use a variable named event in markup event handlers:

<button onclick="alert(event)">See the event</button>

This works, because the browser automatically creates a function handler with the given body and event as the argument.

Internet Explorer way

Internet Explorer provides a global object window.event, which references the last event. And before IE9 there are no arguments in the handler.

So, it works like this:

// handler without arguments
element.onclick = function() {
  // window.event - is the event object
}

Cross-browser solution

A generic way of getting the event object is:

element.onclick = function(event) {
    event = event || window.event

    // Now event is the event object in all browsers.
}

The inline variant

Both standards-compilant browsers and IE make is possible to access event variable in markup handlers.

<input type="button" onclick="alert(event.type)" value="Alert event type"/>

For older IE, the handler has no arguments, so event will reference a global variable, for other browsers, the handler will recieve event as the first argument. So, using event in markup handler is cross-browser.

Summary

The event object contains valuable information about the details of event.

It is passed as first argument to the handler for most browsers and via window.event for IE.

So, for a JavaScript handler we’d use:

element.onclick = function(event) {
    event = event || window.event

    // Now event is the event object in all browsers.
}

And, for a markup handler, just event will do.

Tutorial

Donate

Donate to this project