You are here: Reference > JavaScript > client-side > event handling > objects > event

event object

Browser support:
Represents an object that contains information about an event that has occurred.
Event models in browsers are different. There is only one sort of event object in Internet Explorer before version 9, while other browsers support different event objects to provide the necessary data for each different event.
You can access the event object differently in different browsers:
  • The window.event property is supported by Internet Explorer, Opera, Google Chrome and Safari. It returns a reference to an event object that is filled based on the current event.
    In Internet Explorer, the event object always has the same members, regardless of the event, but only a part of them is filled based on the current event.
    In Opera, Google Chrome and Safari, the type of the event object depends on the event.
  • In Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9, when an event occurs, an event object is initialized and passed to the event handlers as the first parameter. The type of the event object depends on the current event.
    In Internet Explorer before version 9, an event object is passed to an event handler only if it is registered with the attachEvent method. If an event listener is registered with the attachEvent method, the passed event object is a copy of the window.event object in all Internet Explorer versions.
The registration of event handlers is also different:
  • event handlers can be registered by inline event properties (e.g. obj.onclick = handler)
  • with the addEventListener method in Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9
  • with the attachEvent method in Internet Explorer and Opera.
You can see in the examples below how it works in practice.
Event propagation and capturing:
There are two types of events, one propagates up the DOM hierarchy, the other does not (bubbles property).
When an event occurs, it is dispatched to the target element first. The target element is the element on which the event occurred (target and srcElement properties). If the event propagates up, then it will be dispatched to the ancestor elements of the target element in the DOM hierarchy. The propagation can be stopped with the stopPropagation method and the cancelBubble property.
An event is always dispatched to the target element first, except if the event is captured.
The capturing mechanism works differently in different browsers.
  • In Internet Explorer, the setCapture method can be used for set the mouse capture to an object. If an object has capture, then the capturable events will be dispatched to the object first and if an event propagates up, then it will be dispatched to the ancestor elements of the object after. If an event is captured, then it will not be dispatched to the original target element. At most one object can capture the mouse events at the same time.
  • In Firefox, Opera, Google Chrome and Safari, events can be captured by event listeners, not by objects. Internet Explorer also supports this mechanism from version 9. The addEventListener method can be used to register event listeners for capturing.
    1. When an event occurs, the event listeners that capture the event are called (capturing phase).
    2. After this phase, the event will be dispatched to the original target element (target phase).
    3. Finally, if the event propagates up, then it will be dispatched to the ancestor elements of the original target element (bubbling phase).
    The example on the page for the eventPhase property demonstrates this mechanism.
If an object captures the mouse events with the setCapture method, then it captures the events for the entire browser window.
If an object registers an event listener for capturing with the addEventListener method, then the event listener captures only the events that occur on the element or its descendants.
Canceling the default action of an event:
For some events, it is possible to suppress the default action implemented by the browser. For example, when the onclick event is canceled for a checkbox, then clicking on the checkox does not change its checked state. Events can be canceled with the preventDefault method and the returnValue property, or by returning false from an event handler.

Syntax:

Properties that reference the object:
window.event
Methods that return the object:
+object.createEvent (eventType)
Related objects:
document.createEventObject ([eventObjToClone])
The base interface, through which you can add new functionalities to the event object, is the Event interface.
You can find several other interfaces on this page that are inherited from the Event interface. These interfaces represent the available data for different event types.
A part of the event properties and methods is accessible to all event types, the rest can only be used for certain event types. This page contains all event members that are supported by at least one of the event objects.
If you want to know what event objects support a member, see the page for the Event interface. If you need a summary of events and event types, see the page for events in JavaScript.

Possible members:

Properties
Methods
altKey
Sets or retrieves a Boolean value that indicates whether the left or right ALT key was down at the time when the event occurred.
altLeft
Sets or retrieves a Boolean value that indicates whether the left ALT key was down at the time when the event occurred.
attrChange
9
Returns an integer that specifies the type of the action that modified an attribute.
attrName
9
Retrieves a string that specifies the name of the modified attribute.
bookmarks
Represents a collection of ADO bookmarks associated with the rows affected by the current event.
boundElements
Represents a collection of elements bound to the data set on which the current event occurred.
bubbles
9
Returns a Boolean value that indicates whether the current event can propagate up the DOM hierarchy or not.
button
Sets or retrieves the mouse button(s) that were pressed at the time when the current event was fired.
cancelable
9
Returns a Boolean value that indicates whether the current event can be canceled or not.
cancelBubble
9
Sets or retrieves a Boolean value that indicates whether the current event should propagate up the DOM hierarchy, or not.
charCode
9
Retrieves the Unicode character code of the key that generated the onkeypress event.
clientX
Sets or returns the x-coordinate of the mouse pointer relative to the top-left corner of the browser window's client area.
clientY
Sets or returns the y-coordinate of the mouse pointer relative to the top-left corner of the browser window's client area.
ctrlKey
Sets or retrieves whether the left or right CTRL key was down at the time when the event occurred.
ctrlLeft
Sets or retrieves whether the left CTRL key was down at the time when the event occurred.
currentTarget
9
Returns a reference to the element whose event listener is being processed.
data
839.5
Returns the characters entered in case of the textInput event or the contents of the message for the onmessage event.
dataFld
Sets or returns the name of the modified data column in case of the oncellchange event.
dataTransfer
3.5
Represents a drag-and-drop operation.
detail
9
Returns an integer value that specifies additional information about the event.
domain
9.5
10
Returns the hostname of the server that served the document that caused the onmessage event.
eventPhase
9
Returns an integer value that indicates the current processing phase of an event.
explicitOriginalTarget
Returns a reference to the exact object on which the event originally occurred.
fromElement
Returns a reference to the object that lost the active state or that the mouse pointer left.
horizontalOverflow
Retrieves a Boolean value that indicates the horizontal overflow state of an element when the overflowchanged event occurred.
isChar
Returns whether the character that belongs to the current event is a key character or not.
isTrusted
9
Returns a Boolean value that indicates whether the event is a trusted event or not.
keyCode
Sets or retrieves the Unicode character code of the key that generated the onkeypress event and the Unicode key code of the key that generated the onkeydown and onkeyup events.
lastEventId
310.6
Returns the identifier of the last event in case of onmessage events.
layerX
9
Retrieves the x-coordinate of the mouse pointer relative to the top-left corner of the closest positioned ancestor element of the element that fires the event.
layerY
9
Retrieves the y-coordinate of the mouse pointer relative to the top-left corner of the closest positioned ancestor element of the element that fires the event.
metaKey
9
Retrieves a Boolean value that indicates whether the META key was down at the time when the event occurred.
newValue
9
Retrieves a string that specifies the current value of the modified attribute or TextNode element.
offsetX
Sets or retrieves the x-coordinate of the mouse pointer relative to the top-left corner of the offsetParent element of the element that fires the event.
offsetY
Sets or retrieves the y-coordinate of the mouse pointer relative to the top-left corner of the offsetParent element of the element that fires the event.
orient
Retrieves whether the visibility of the horizontal or vertical scrollbar changed when the overflowchanged event occurred.
origin
8310
Returns the scheme, hostname and port of the document that caused the onmessage event.
originalTarget
Returns a reference to the object on which the event originally occurred.
pageX
9
Retrieves the x-coordinate of the mouse pointer relative to the top-left corner of the document.
pageY
9
Retrieves the y-coordinate of the mouse pointer relative to the top-left corner of the document.
prevValue
9
Retrieves a string that specifies the previous value of the modified attribute or TextNode element.
propertyName
Specifies or retrieves a string that contains the name of the property that is changed.
qualifier
Sets or retrieves the name of the default data member. Use this property with data binding events (such as ondatasetcomplete).
rangeOffset
Returns the end position of the current selection relative to the element referred to by the rangeParent.
rangeParent
Returns a reference to the element where the selection ends.
reason
Sets or retrieves an integer value that indicates whether the data transfer was successful or not. Use this property with ondatasetcomplete events.
recordset
Sets or retrieves a reference to the default record set in a data source.
relatedNode
9
Returns a reference to the node on which the mutation event occurred.
relatedTarget
9
Returns a reference to the related element in case of onmouseover, onmouseout, dragenter and dragexit events.
repeat
Sets or retrieves a Boolean value that indicates whether the onkeydown event is being repeated (a key has been down long enough).
returnValue
Sets or retrieves a Boolean value that indicates whether the current event is canceled.
screenX
Sets or retrieves the x-coordinate of the mouse pointer relative to the top-left corner of the screen.
screenY
Sets or retrieves the y-coordinate of the mouse pointer relative to the top-left corner of the screen.
shiftKey
Sets or retrieves a Boolean value that indicates whether the left or right SHIFT key was down at the time when the event occurred.
shiftLeft
Sets or retrieves a Boolean value that indicates whether the left SHIFT key was down at the time when the event occurred.
source
839.5
Returns a reference to the window object that contains the document that caused the onmessage event.
srcElement
Retrieves a reference to the object on which the event occurred.
srcFilter
Specifies or retrieves a reference to the filter object that generated the onfilterchange event.
srcUrn
Sets or retrieves the Uniform Resource Identifier (URI) of the behavior that fired the event.
target
9
Returns a reference to the object on which the event originally occurred.
timeStamp
9
Returns the time in milliseconds when the current event occurred.
toElement
Returns a reference to the object that the mouse pointer entered.
type
Retrieves a string that represents the type of the event, such as "mouseout", "click", etc.
uri
9.5
10
Returns the location of the document that caused the onmessage event.
verticalOverflow
Retrieves a Boolean value that indicates the vertical overflow state of an element when the overflowchanged event occurred.
view
9
Returns a reference to the AbstractView object where the event occurred.
wheelDelta
Returns an integer value indicating the distance that the mouse wheel rolled.
which
9
Returns the Unicode character or key code of the key or the identifier of the mouse button that was pressed when the current event fired.
x
Sets or retrieves the x-coordinate of the mouse pointer relative to the top-left corner of the closest relatively positioned ancestor element of the element that fires the event.
y
Sets or retrieves the y-coordinate of the mouse pointer relative to the top-left corner of the closest relatively positioned ancestor element of the element that fires the event.
The event object supports several constants. A part of them is accessible to all event types, the rest can only be used for certain event types. If you need a complete list of event constants, please see the members of the Event interface and the page for the interfaces inherited from the Event interface.

Example HTML code 1:

This example illustrates the use of the event object for inline event handlers. An instance of the event object is passed to the onclick event handler as the first parameter, in Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9. An inline event handler behaves like a function, so the first parameter can be passed through the arguments object. See Example 2 and 3 as well.
<head>
    <script type="text/javascript">
        function GetEventType (eventObj) {
            if (eventObj) {
                alert ("The event handler got the event object as the first parameter.");
            }
            else {  // Internet Explorer before version 9
                alert ("The window.event object will be used.");
                eventObj = window.event;
            }

                // now the eventObj variable contains a reference to an instance of the event object
            alert ("The type of the event: " + eventObj.type);
        }
    </script>
</head>
<body>
    <button onclick="GetEventType (arguments[0]);">Click on me!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 2:

This example is similar to the previous one, but it uses the variable named 'event' instead of the arguments object to get the event object, because the first parameter of inline event handlers is always named as 'event' in Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9. Furthermore, since the members of the window object can be accessed directly (without the 'window.' prefix) and the window.event property is supported by Internet Explorer, the variable named 'event' refers to the global event object in Internet Explorer before version 9. So the GetEventType method always gets the event object as the first parameter. See the next example as well.
<head>
    <script type="text/javascript">
        function GetEventType (eventObj) {
            if (eventObj) {
                alert ("The event handler got the event object as the first parameter.");
            }

                // now the eventObj variable contains a reference to an instance of the event object
            alert ("The type of the event: " + eventObj.type);
        }
    </script>
</head>
<body>
    <button onclick="GetEventType (event);">Click on me!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 3:

This example is the conclusion of the previous one. The GetEventType method does not need to check the existence of the eventObj parameter, because it always refers to the event object, so using a parameter named 'event' instead of 'eventObj' is a logical choice and results in more readable code.
<head>
    <script type="text/javascript">
        function GetEventType (event) {
                // the event variable contains a reference to an instance of the event object
            alert ("The type of the event: " + event.type);
        }
    </script>
</head>
<body>
    <button onclick="GetEventType (event);">Click on me!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 4:

This example registers an event handler in a shorthand form (inline event property). The event handler gets an instance of the event object as the first parameter, in Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9. In Internet Explorer before version 9, the window.event property is used. See the next example as well.
<head>
    <script type="text/javascript">
        function GetEventType (eventObj) {
            if (eventObj) {
                alert ("The event handler got the event object as the first parameter.");
            }
            else {  // Internet Explorer before version 9
                alert ("The window.event object will be used.");
                eventObj = window.event;
            }

                // now the eventObj variable contains a reference to an instance of the event object
            alert ("The type of the event: " + eventObj.type);
        }

        function Init () {
            var button = document.getElementById ("myButton");
            button.onclick = GetEventType;
        }
    </script>
</head>
<body onload="Init ();">
    <button id="myButton">Click on me!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 5:

The eventObj parameter used by the previous example is equivalent to the window.event property in Opera, Google Chrome and Safari, so using a parameter named 'event' instead of 'eventObj' is a logical choice and results in more readable code.
<head>
    <script type="text/javascript">
        function GetEventType (event) {
            if (!event) {   // Internet Explorer before version 9
                event = window.event;
            }

                // now the event variable contains a reference to an instance of the event object
            alert ("The type of the event: " + event.type);
        }

        function Init () {
            var button = document.getElementById ("myButton");
            button.onclick = GetEventType;
        }
    </script>
</head>
<body onload="Init ();">
    <button id="myButton">Click on me!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 6:

This example registers an event handler with the addEventListener and attachEvent methods. The event handler always gets an instance of the event object as the first parameter, in all commonly used browsers.
<head>
    <script type="text/javascript">
        function GetEventType (event) {
                // the event variable contains a reference to an instance of the event object
            alert ("The type of the event: " + event.type);
        }

        function Init () {
            var button = document.getElementById ("myButton");
            if (button.addEventListener) {  // all browsers except IE before version 9
                button.addEventListener ("click", GetEventType, false);
            } else if (button.attachEvent) {    // Internet Explorer before version 9
                button.attachEvent ('onclick', GetEventType);
            }
        }
    </script>
</head>
<body onload="Init ();">
    <button id="myButton">Click on me!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 7:

This example shows how to pass the object to an event handler on which the event has been registered. Note that the object on which the event has occurred and the object referred to by this may be different. See the this keyword for details.
<head>
    <script type="text/javascript">
        function ChangeColor (elem) {
            elem.style.color = "#ff0000";
        }
    </script>
</head>
<body>
    <button onclick="ChangeColor (this);">Change my text color to red!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 8:

This example is equivalent to the previous one, but it uses the addEventListener and attachEvent methods to register an event handler for the onclick event.
<head>
    <script type="text/javascript">
        function ChangeColor (elem) {
            elem.style.color = "#ff0000";
        }

        function OnDocLoad () {
            var button = document.getElementById ("myButton");
            if (button.addEventListener) {  // all browsers except IE before version 9
                button.addEventListener ("click", function () {ChangeColor (button)}, false);
            } else if (button.attachEvent) {    // Internet Explorer before version 9
                button.attachEvent ('onclick', function () {ChangeColor (button)});
            }
        }
    </script>
</head>
<body onload="OnDocLoad ();">
    <button id="myButton">Change my text color to red!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 9:

This example shows how to register object methods as event handlers.
<head>
    <script type="text/javascript">
            // ColorChanger object
        function ColorChanger (elem, colorTo) {
            this.Init (elem, colorTo);
        }

        ColorChanger.prototype.Init = function (elem, colorTo) {
            this.elem = elem;
            this.colorTo = colorTo;

                // save a reference to the current object
            var _this = this;
                /* use the saved reference within the registered function 
                 (the 'this' statement within the registered function refers to the function
                 not the current instance of ColorChanger) */
            this.elem.onclick = function () {_this.ChangeColor ()};
        }

        ColorChanger.prototype.ChangeColor = function () {
            this.elem.style.color = this.colorTo;
        }
        

            // Attach ColorChanger instances to the buttons
        function OnDocLoad () {
            var button1 = document.getElementById ("button1");
            var button2 = document.getElementById ("button2");

            var colorChanger1 = new ColorChanger (button1, "#ff0000", 1);
            var colorChanger2 = new ColorChanger (button2, "#0000ff", 2);
        }
    </script>
</head>
<body onload="OnDocLoad ()">
    <button id="button1">Change my text color to red!</button>
    <button id="button2">Change my text color to blue!</button>
</body>
Did you find this example helpful? yes no

Related pages:

External links:

User Contributed Comments

Post Content

Post Content