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) { |
It is also possible to use a named function:
1 | function doSomething(event) { |
5 | 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:
2 | element.onclick = function () { |
Cross-browser solution
A generic way of getting the event object is:
1 | element.onclick = function (event) { |
2 | event = event || window.event |
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:
1 | element.onclick = function (event) { |
2 | event = event || window.event |
And, for a markup handler, just event
will do.