JavaScript & jQuery Tutorials

JQ Home Right Arrow JQ Advanced Right Arrow The Event Object

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.

  1. The event object is guaranteed to be passed to the event handler.
  2. The original event properties can be accessed from event.originalEvent.
  3. 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 the false parameter, as an example ( $('aSelector').on('anEventType', false); ) will automatically call the event.stopPropagation() and event.preventDefault() methods on it.

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.clientXThe mouse position relative to the left edge of the viewable window (X-axis).
event.clientYThe mouse position relative to the top edge of the viewable window (Y-axis).
event.currentTargetThe DOM element in progress within the event bubbling phase.
event.dataAn optional data map passed to an event method when the currently executing handler is attached.
event.delegateTargetThe element that the in progress jQuery event handler was attached to.
event.namespaceThe namespace specified on event triggering.
event.pageXThe mouse position relative to the left edge of the document (X-axis).
event.pageYThe mouse position relative to the top edge of the document (Y-axis).
event.relatedTargetThe other DOM element, if it exists, involved in mouseout and mouseover events.
event.resultThe last value returned by an event handler triggered by this event, unless the value was undefined.
event.targetThe DOM element, or descendant thereof, that initiated the event.
event.timeStampThe difference in milliseconds between the creation of this event by the browser and UTC (January 1, 1970).
event.typeDescription of the event.
event.whichIndicates the key or button that was pressed for keyboard and mouse events.

Event Object Methods

The event.isDefaultPrevented() and
        event.preventDefault() Methods go to top of page 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. go to top of page Top.



The event.isImmediatePropagationStopped() and
        event.stopImmediatePropagation() Methods go to top of page 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 go to top of page 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 go to top of page 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();
});

a picture of curry

The page coordinates are:

The viewable page coordinates are:

The event.currentTarget and
        event.delegateTarget Properties go to top of page 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);
  });
});

Press the button below to action the above code:

               

We will show a message here for the mouse button press.


The event.data Property go to top of page 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>');
  }
});

Press the button below to action the above code:

We will show a message here.


The event.namespace Property go to top of page 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.



Press the button below to action the above code:

The event.relatedTarget Property go to top of page 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 go to top of page 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.



Press the button below to action the above code:

The event.target Property go to top of page Top

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.');
 });
});

div12. Some initial text.



The event.timeStamp Property go to top of page 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.



Press the button below to action the above code:

The event.type Property go to top of page 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.



Press the button below to action the above code:

The event.which Property go to top of page 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: Loading & Browser 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.

Reference

Methods

Attributes & Properties - .css() method
Attributes & Properties - .html() method
Events - .click() method
Events - .mousemove() method
Events - .mouseout() method
Events - .mouseover() method
Events - .on() method
Events - .one() method
Manipulation - append() method
Manipulation - .text() method
Event Object - event.isDefaultPrevented() method
Event Object - event.isImmediatePropagationStopped() method
Event Object - event.isPropagationStopped() method
Event Object - event.preventDefault() method
Event Object - event.stopImmediatePropagation() method
Event Object - event.stopPropagation() method

Properties

Event Object - event.clientX property
Event Object - event.clientY property
Event Object - event.currentTarget property
Event Object - event.data property
Event Object - event.delegateTarget property
Event Object - event.namespace property
Event Object - event.pageX property
Event Object - event.pageY property
Event Object - event.relatedTarget property
Event Object - event.result property
Event Object - event.target property
Event Object - event.timestamp property
Event Object - event.type property
Event Object - event.which property



  

go to jQuery home page jQuery Home go to top of page Top