The Event ObjectS2C Home « The Event Object
In this lesson we investigate the jQuery Event object and how to utilize it for use in our webpages.
jQuery creates its own Event object using the Javascript Event object that is bound by the browser in accordance with the level 3 Document Object Model Events definition, the W3C Working Draft
.
- The event object is guaranteed to be passed to the event handler.
- The original event properties can be accessed from
event.originalEvent
. - When an event reaches an element, all handlers bound to that event type for the element are fired. If multiple handlers are registered for the element, they will always execute in the order in which they
were bound. When all handlers have finished executing, the event continues along the normal event propagation path.
- A handler can prevent the event from bubbling further up the document tree, thus preventing handlers on those elements from running, by calling the
event.stopPropagation()
method. - If other handlers are attached to the current element these will run however. This can be prevented by calling the
event.stopImmediatePropagation()
method. - To cancel any default action that the browser may have for this event, call the
event.preventDefault()
method. - Returning
false
from an event handler or calling an event handler with thefalse
parameter, as an example ($('aSelector').on('anEventType', false);
) will automatically call theevent.stopPropagation()
andevent.preventDefault()
methods on it.
- A handler can prevent the event from bubbling further up the document tree, thus preventing handlers on those elements from running, by calling the
Event Object Methods & Properties | Description |
---|---|
Methods | |
event.isDefaultPrevented() | Return a boolean dependant upon event.preventDefault() ever being called on this event object. |
event.isImmediatePropagationStopped() | Return a boolean dependant upon event.stopImmediatePropagation() ever being called on this event object. |
event.isPropagationStopped() | Return a boolean dependant upon event.stopPropagation() ever being called on this event object. |
event.preventDefault() | Prevents an event's default action from triggering. |
event.stopImmediatePropagation() | Stop other event handlers being called. |
event.stopPropagation() | Stop current event bubbling up the DOM tree, preventing parent handler notification of the event. |
Properties | |
event.clientX | The mouse position relative to the left edge of the viewable window (X-axis). |
event.clientY | The mouse position relative to the top edge of the viewable window (Y-axis). |
event.currentTarget | The DOM element in progress within the event bubbling phase. |
event.data | An optional data map passed to an event method when the currently executing handler is attached. |
event.delegateTarget | The element that the in progress jQuery event handler was attached to. |
event.namespace | The namespace specified on event triggering. |
event.pageX | The mouse position relative to the left edge of the document (X-axis). |
event.pageY | The mouse position relative to the top edge of the document (Y-axis). |
event.relatedTarget | The other DOM element, if it exists, involved in mouseout
and mouseover events. |
event.result | The last value returned by an event handler triggered by this event, unless the value was undefined . |
event.target | The DOM element, or descendant thereof, that initiated the event. |
event.timeStamp | The difference in milliseconds between the creation of this event by the browser and UTC (January 1, 1970). |
event.type | Description of the event. |
event.which | Indicates the key or button that was pressed for keyboard and mouse events. |
Event Object Methods
The event.isDefaultPrevented()
and
event.preventDefault()
Methods Top
event.isDefaultPrevented()
- Return a boolean dependant upon event.preventDefault()
ever being called on this event object.
event.preventDefault()
- Prevents an event's default action from triggering.
In the example below we show a new message in the 'div' element with an id of 'div10' whenever the mouse is clicked on this anchor 'a' element within this element.
We are stopping the default action for the element from occuring, which in this case is redirecting to the link, by calling the event.preventDefault()
Event object method on the element.
$(function(){
$('#div10 a').on('click', function(event) {
event.preventDefault();
$('#div10').append('Has event.preventDefault()
been called on this event object? '
+ event.isDefaultPrevented() + '<br/>');
});
});
div10. Click this link. Top.
The event.isImmediatePropagationStopped()
and
event.stopImmediatePropagation()
Methods Top
event.isImmediatePropagationStopped()
- Return a boolean dependant upon event.stopImmediatePropagation()
ever being called on this event object.
event.stopImmediatePropagation()
- Stop other event handlers being called.
In the example below we show a new message in the 'div' element with an id of 'div13' whenever the mouse is clicked on this element stating immediate propagation stopped.
We are stopping other handlers from propogating so we will never see the output from the second handler.
$(function(){
$('#div11').on('click', function(event) {
event.stopImmediatePropagation();
$('#div11').append('Has event.stopImmediatePropagation()
been called on this event obj? '
+ event.isImmediatePropagationStopped() + '<br/>');
});
$('#div11').on('click', function(event) { // Following will not execute
$('#div11').append('We will never see this text');
});
});
div11. Some inital text.
The event.isPropagationStopped()
and
event.stopPropagation()
Methods Top
event.isPropagationStopped()
- Return a boolean dependant upon event.stopPropagation()
ever being called on this event object.
event.stopPropagation()
- Stop current event bubbling up the DOM tree, preventing parent handler notification of the event.
In the example below we show two new messages in the 'div' element with an id of 'div13' the first time the mouse is clicked on this element. One before event.stopImmediatePropagation()
has been called and one after.
$(function(){
$('#div13').one('click', function(event) {
$('#div13').append('Has event.isPropagationStopped()
been called on this event object? '
+ event.isPropagationStopped() + '<br/>');
event.stopPropagation();
$('#div13').append('Has event.isPropagationStopped()
been called on this event object? '
+ event.isPropagationStopped() + '<br/>');
});
});
div13. Some initial text.
Event Object Properties
The event.clientX
, event.clientY
and
event.pageX
, event.pageY
Properties Top
event.clientX
- The mouse position relative to the left edge of the viewable window (X-axis).
event.clientY
- The mouse position relative to the top edge of the viewable window (Y-axis).
event.pageX
- The mouse position relative to the left edge of the document (X-axis).
event.pageY
- The mouse position relative to the top edge of the document (Y-axis).
In the example below we show two new message in the 'p' elements below every time the mouse moves over the image with the id of 'curry1'.
When the mouse moves while over the image, we trigger off the mousemove
JavaScript event on the 'image'. This then fires off the
$('#curry1').mousemove(function(){})
code which outputs the messages.
$(function(){
$('#curry1').mousemove(function(event) {
var pageCoords = '(' + event.pageX + ', ' + event.pageY + ' )';
var viewableCoords = '(' + event.clientX + ', ' + event.clientY + ' )';
$('#animspan1').text('( event.pageX, event.pageY ) : ' + pageCoords);
$('#animspan2').text('( event.clientX, event.clientY ) : ' + viewableCoords);
});
$('#curry1').mousemove();
});
The page coordinates are:
The viewable page coordinates are:
The event.currentTarget
and event.delegateTarget
Properties Top
event.currentTarget
- The DOM element in progress within the event bubbling phase.
event.delegateTarget
- Contains the value of the element that the in progress jQuery event handler was attached to.
When we press the left button the first time, we see a difference between our current target (the button) and the delegated target (the ancestor form).
When we press the right button the first time, the current target (the button) and the delegated target (the same button) are equal as the event was directly bound to the button and no delegation occurred.
$(function(){
$('form').one('click', '#btn3', function(event){
$('#scrollspan3').append('*** Delegated event. Current target: ' + event.currentTarget
+ '. Delegated target: ' + event.delegateTarget);
});
$('#btn4').one('click', function(event){
$('#scrollspan3').append('*** Directly bound event. Current target: ' + event.currentTarget
+ '. Delegated target: ' + event.delegateTarget);
});
});
We will show a message here for the mouse button press.
The event.data
Property Top
An optional data map passed to an event method when the currently executing handler is attached.
When we press the button the first time, we pass a map of data to the addText()
function, which outputs a message below.
What we are doing here is passing across the event
object to the function addText(event)
. The map we specify, in our case { param1: '#scrollspan2', param2: 'click was attached from .one()', param3: '**JavaScript event triggered** ' }
gets tagged onto the event.data
property. We then access these parameters in the function via event.data.paramN
and use it as part of the appended data.
$(function(){
$('form').one('click', '#btn2',
{ param1: '#scrollspan2', param2: 'click was attached from .one() ',
param3: '**JavaScript event triggered** ' }, addText);
function addText(event) {
$(event.data.param1).append(event.data.param2 + '<code>' + event.data.param3+ '</code>');
}
});
We will show a message here.
The event.namespace
Property Top
The namespace specified on event triggering.
In the example below when you enter or leave the 'div2' element the mouseenter
and mouseleave
JavaScript events fire but the namespace isn't passed across in the event so is undefined.
When we press the left button we trigger the mouseenter
JavaScript event manually and the event.namespace
parameter gets passed in the object and is output as part of the message.
$(function(){
$('#div2').on({
'mouseenter.ns1': function(event) {
$(this).css({backgroundColor: 'orange', color: 'black'})
.append('**entering "div2. " Namespace: ' + event.namespace);
},
'mouseleave.ns2': function(event) {
$(this).css({backgroundColor: 'green', color: 'white'})
.append('**leaving "div2. " Namespace: ' + event.namespace);
}
});
$('#btn5').on('click', function(){
$('#div2').trigger('mouseenter.ns1');
});
});
div2. Some initial text.
The event.relatedTarget
Property Top
Contains the value of the last value returned by an event handler triggered by this event, unless the value was undefined
.
In the example below when you enter or leave the 'div3' element the mouseover
and mouseout
JavaScript
events fire and we output the event.relatedTarget
as part of the message.
$(function(){
$('#div3').on({
'mouseover.ns1': function(event) {
$(this).css({backgroundColor: 'orange', color: 'black'})
.append('**entering "div3. " Related Target: ' + event.relatedTarget);
},
'mouseout.ns2': function(event) {
$(this).css({backgroundColor: 'green', color: 'white'})
.append('**leaving "div3. " Related Target: ' + event.relatedTarget);
}
});
});
div3. Some initial text.
The event.result
Property Top
The other DOM element, if it exists, involved in mouseout
and mouseover
events.
When we press the button below the first 'click' event fires and stores the event.result property which we retrieve and display with the second event handler.
$(function(){
$('#btn6').on('click', function(event) {
return 'This string will be stored in event.result';
});
$('#btn6').on('click', function(event) {
$('#div4').html(event.result);
});
});
div4. Some initial text.
event.target
ExampleTop
Contains the value of the DOM element, or descendant thereof, that initiated the event.
When we press the mouse button in the division below with an id of 'div12' a message is output displaying the target element.
$(function(){
$('#div12').on('click', function(event) {
$('#div12').append('--The ' + event.target.nodeName + ' element was clicked.<br/ >');
});
});
div12. Some initial text.
The event.timeStamp
Property Top
Contains the value of the difference in milliseconds between the creation of this event by the browser and UTC (January 1, 1970).
When we click the button below twice or more a message is output displaying the elapsed time in milliseconds since the last click.
$(function(){
var prev, elapsed;
$('#btn7').on('click', function(event) {
if ( prev ) {
elapsed = event.timeStamp - prev;
$('#div5').append('Elapsed time since last event: ' + elapsed + ' milliseconds.<br/ >');
}
prev = event.timeStamp;
});
});
div5. Some initial text.
The event.type
Property Top
Contains the value of the description of the event.
When we click the button below the first time, a message is output displaying the description of the event type.
$(function(){
$('#btn8').one('click', function(event) {
$('#div6').append('Event type is: ' + event.type);
});
});
div6. Some initial text.
The event.which
Property Top
Contains a value indicating the key or button that was pressed for keyboard and mouse events.
When we click the mouse button in the div below with an id of 'div7', a message is output.
$(function(){
$('#div7').on('click', function(event) {
if ( event.which == 1 ) {
$('#div7').append('You pressed the left mouse button.
');
}
});
});
div7. Some initial text.
Lesson 5 Complete
In this lesson we looked at the the Event object.
Related Tutorials
jQuery Advanced - Lesson 1: Browser & Loading Events
jQuery Advanced - Lesson 2: Keyboard & Mouse Events
jQuery Advanced - Lesson 3: Form Events
jQuery Advanced - Lesson 4: Event Handler Attachments
What's Next?
In the next lesson we look at the jQuery.Callbacks
object provided by jQuery.
jQuery 3.5 Reference Methods
jQuery Reference - Attributes & Properties - .css()
method
jQuery Reference - Attributes & Properties - .html()
method
jQuery Reference - Events - .click()
method
jQuery Reference - Events - .mousemove()
method
jQuery Reference - Events - .mouseout()
method
jQuery Reference - Events - .mouseover()
method
jQuery Reference - Events - .on()
method
jQuery Reference - Events - .one()
method
jQuery Reference - Manipulation - .append()
method
jQuery Reference - Manipulation - .text()
method
jQuery Reference - Event Object - event.isDefaultPrevented()
method
jQuery Reference - Event Object - event.isImmediatePropagationStopped()
method
jQuery Reference - Event Object - event.isPropagationStopped()
method
jQuery Reference - Event Object - event.preventDefault()
method
jQuery Reference - Event Object - event.stopImmediatePropagation()
method
jQuery Reference - Event Object - event.stopPropagation()
method
jQuery 3.5 Reference Properties
jQuery Reference - Event Object - event.clientX
property
jQuery Reference - Event Object - event.clientY
property
jQuery Reference - Event Object - event.currentTarget
property
jQuery Reference - Event Object - event.data
property
jQuery Reference - Event Object - event.delegateTarget
property
jQuery Reference - Event Object - event.namespace
property
jQuery Reference - Event Object - event.pageX
property
jQuery Reference - Event Object - event.pageY
property
jQuery Reference - Event Object - event.relatedTarget
property
jQuery Reference - Event Object - event.result
property
jQuery Reference - Event Object - event.target
property
jQuery Reference - Event Object - event.timestamp
property
jQuery Reference - Event Object - event.type
property
jQuery Reference - Event Object - event.which
property