Categories:

JavaScript Kit > JavaScript Reference > Here

Event Object

Last updated: March 15th, 2009

The Event object keeps tracks of various events that occur on the page, such as the user moving the mouse or clicking on the link, and allows you to react to them inside your scripts.

Related Tutorials

Cross browser Event object

The Event model is implemented differently in IE and Firefox. In IE, there is an explicit window.event object that logs any details of an event (ie: onclick) when it occurs, while in Firefox and other W3c compliant browsers, an inexplicit Event object is automatically passed into the function associated with the event handler that contains similar info about the event. You can equalize this difference in your event handler functions to access the Event object generically with the detection in red below:

document.onclick=function(e){
 var evt=window.event || e //evt evaluates to window.event or inexplicit e object, depending on which one is defined
 alert(evt.clientX) //do something with evt
}

Even with access to the Event object equalized amongst browsers, there is still the issue of IE and Firefox supporting different properties/ methods within the Event object. Below lists the related properties and methods separately for the two divergent Event objects.

IE Event Object

In IE, the event object is accessed completely through the explicit object "window.event". It supports the following properties:

Properties

Properties Description W3C/ Firefox Equivalent?
altKey, ctrlKey, shiftKey Boolean properties that indicate whether the Alt, Ctrl, and Shift keys were pressed at time of the event. Same.
button An integer indicating which mouse button was pressed or released, 1 = left, 2 = right, 4 = middle. If multiple buttons are pressed, the value is the sum of both buttons, such as 3 (1+2) for left and right. In Firefox browsers, the same property returns slightly different numbers. Here's an example:

document.onmousedown=function(e){
 var evt=window.event || e //cross browser event object
 alert(evt.button)
}

If you wish to detect when the right mouse button has been clicked to suppress the default browser's context menu from appearing, simply returning false inside an "onclick" or "onmousedown" event will have no effect. You will need to use the "oncontextmenu" event instead:

document.oncontextmenu=function(){
 return false //stops the browser context menu from appearing on right click
}

Same, but different return values.
cancelBubble Set to true to prevent the event from bubbling. In non IE browsers, use e.stopPropagation() instead. To cancel event bubbling across browsers, you should check for support for e.stopPropagation(), and proceed accordingly:

function preventbubble(e){
 if (e && e.stopPropagation) //if stopPropagation method supported
  e.stopPropagation()
 else
  event.cancelBubble=true
}

stopPropagation()
clientX, clientY Returns the mouse coordinates at the time of the event relative to upper-left corner of the window. These two properties are identical in the W3C/ Firefox event model as well. The following example displays in the status bar the current coordinates of the mouse as it moves:

document.onmousemove=function(e){
 var evt=window.event || e //cross browser event object
 window.status=evt.clientX+" : "+evt.clientY
}

Same.
fromElement, toElement For mouseover and mouseout events, these properties indicate the elements the mouse is leaving from and moving into, respectively. The W3C/ Firefox event model uses a different property, "relatedTarget", instead, that simply returns the corresponding element based on the event type (mouseover or mouseout).

See "relatedTarget" in the Firefox section below for more info plus demonstration.

relatedTarget
keyCode Property indicating the Unicode for the key pressed. Use String.fromCharCode(keyCode) to convert code to string.

For a complete overview on detecting and responding to keyboard events, see the reference page "Keyboard and Mouse buttons events".

charCode
offsetX, offsetY Returns the mouse coordinates relative to a positioned (absolute or relative) element. If the event occurred outside a positioned element, than the upper left corner of the document is used instead. layerX, layerY
returnValue Set to false to cancel any default action associated with the event. In W3C/Firefox browsers, call the function e.preventDefault() instead. preventDefault()
srcElement The element that the event originated from, which may differ from the element the event was explicitly assigned to due to event bubbling. Consider the example where you assign a click event to divA that contains a child divB. Clicking inside divB, event.srcElement returns divB, the element the event occurred on, and not divA, the element the event was assigned to.

Firefox and other modern browsers do not support the "srcElement" property but instead the equivalent e.target property. To equalize this difference between all browsers, you can test whether the event object supports e.target, and if not, extend it with a custom e.target property using e.srcElement instead:

function myevent(e){
 var evt=window.event || e
 if (!evt.target) //if event obj doesn't support e.target, presume it does e.srcElement
  evt.target=evt.srcElement //extend obj with custom e.target prop
 //do something with evt.target, which is cross browser
}

target
type A string indicating the type of event, such as "mouseover", "click", etc. Same.

Mozilla/ Firefox Event Object

In Firefox+, the Event object is accessed by passing an event parameter into the event handler function in question.

Properties

Properties Description IE Equivalent?
altKey, ctrlKey, metaKey, shiftKey Boolean properties that indicate whether the Alt, Ctrl, Meta, and Shift keys were pressed at time of the event. Same, though IE doesn't support "metaKey".
bubbles A Boolean value indicating whether or not the event bubbles. N/A
button An integer indicating which mouse button was pressed or released, 0 = left, 2 = right, 1 = middle. Slightly different in IE, as described above. Same, but different return values.
cancelable A Boolean value indicating whether or not the event can be cancelled. N/A
charCode Property indicating the Unicode for the key pressed. Use String.fromCharCode(which) to convert code to string.

For a complete overview on detecting and responding to keyboard events, see the reference page "Keyboard and Mouse buttons events".

keyCode
clientX, clientY Returns the mouse coordinates at the time of the event relative to upper-left corner of the window. Same as in IE (see above for more info). Same.
currentTarget The element in which the event was assigned to. Consider the example where you assign a click event to divA that contains a child divB. Clicking inside divB, e.currentTarget references divA (the element the event was assigned to) while e.target returns divB, the element the event occurred on. N/A
eventPhase An integer value indicating which phase of the event flow this event is being processed in. One of CAPTURING_PHASE (1), AT_TARGET (2) or BUBBLING_PHASE (3). N/A
layerX, layerY Returns the mouse coordinates relative to a positioned (absolute or relative) element at the time of the event. If the event occurred outside a positioned element, than the upper left corner of the document is used instead. IE uses the properties offsetX and offsetY instead. offsetX, offsetY
pageX, pageY Returns the mouse coordinates relative to the top left corner of the visible page at the time of the event. They are equivalent to:
  • pageX: window.pageXOffset+e.clientX
  • pageY: window.pageYOffset+e.clientY
N/A
relatedTarget On a "mouseover" event it indicates the node that the mouse has left. On a "mouseout" event it indicates the node the mouse has moved into.

The "relatedTarget" property (or "fromElement" and "toElement" in IE) is commonly used to detect whether the mouse is still within a container during a "mouseover" or "mouseout" event associated with it. Due to event bubbling, a "mouseover" event on a container for example can fire multiple times if the container contains any nested elements or even just text, as the mouse travels from one nested element to the next.

The following example shows the ID of the element the mouse is coming from and moving into during  a "mouseover" or "mouseout" event, respectively.

Demo (roll your mouse over the blocks below):

Source:

<div id="outerdiv" style="width:130px; height:130px; border:1px solid black; background:black; padding:30px;">
<div id="innerdiv" style="width:80px; height:80px; border:1px solid black; background:white; padding:20px"></div>
</div>

<div id="statusfrom"></div>
<div id="statusto"></div>



<script type="text/javascript">

function showtofrom(e){
 var evt=window.event || e
 if (evt.type=="mouseover"){ //for onmouseover event
  var fromElement=evt.fromElement || evt.relatedTarget
  statusdiv1.innerHTML='From Element: ' + fromElement.id
 }
 else{ //for onmouseout event
  var toElement=evt.toElement || evt.relatedTarget
  statusdiv2.innerHTML='To Element: ' + toElement.id
 }
}

var statusdiv1=document.getElementById("statusfrom")
var statusdiv2=document.getElementById("statusto")

document.body.onmouseover=showtofrom
document.body.onmouseout=showtofrom

</script>

fromElement, toElement
screenX, screenY Returns the coordinates of the mouse relative to the screen when the event fired. N/A
target The element that the event originated from, which may differ from the element the event was explicitly assigned to. Consider the example where you assign a click event to divA that contains a child divB. Clicking inside divB, e.target returns divB, the element the event occurred on. srcElement
timestamp Returns the time (in milliseconds since the epoch) the event was created, for example, when a key was pressed (onkeypress). Not all events return a timestamp. N/A
type A string indicating the type of event, such as "mouseover", "click", etc. Same.
which NS4/NS6+ legacy property indicating the Unicode for the key pressed. Identical to "charCode", except this property works in NS4 as well.. keyCode

Methods

Methods Description IE Equivalent?
preventDefault() Cancels any default action associated with the event. To accomplish the same in IE, return false inside the function assigned to the event in question instead.

The following example disables the default action of all links on the page that proceeds the script when clicked on, which is to go to the URL specified in its "href" attribute:

function disablelink(e){
 var evt=window.event || e
 if (evt.preventDefault) //supports preventDefault?
  evt.preventDefault()
 else //IE browser
  return false
}

var alllinks=document.getElementsByTagName("a")
for (var i=0; i<alllinks.length; i++){
 alllinks[i].onclick=disablelink
}

returnValue
stopPropagation() Set to true to prevent the event from bubbling. Too accomplish the same in IE, set event.cancelBubble to true instead.

Consider divA that contains divB inside it. When you assign a click event to divA, clicking inside divB by default will also trigger the event due to event bubbling. To prevent that from happening, you can invoke stopPropagation() on the divB node so events occurring inside it do not continue to travel upwards:

Demo:

Code:

divB.onclick=function(e){
 if (e && e.stopPropagation) //if stopPropagation method supported
  e.stopPropagation()
 else
  event.cancelBubble=true
}

cancelBubble

Reference List

Right column

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info