Obtaining the event object

来源:互联网 发布:如何进行wifi网络认证 编辑:程序博客网 时间:2024/05/24 00:58

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:

1function doSomething(event) {
2  // we've got the event
3}
4 
5element.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:

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

Cross-browser solution

A generic way of getting the event object is:

1element.onclick = function(event) {
2    event = event || window.event
3 
4    // Now event is the event object in all browsers.
5}

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:

1element.onclick = function(event) {
2    event = event || window.event
3 
4    // Now event is the event object in all browsers.
5}

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

0 0
原创粉丝点击