jQuery Event attributes

Event attributes

A jQuery event handler standardizes certain attributes:

  • .target
    represents the DOM element that initiated the event.
  • .relatedTarget
    represents the other DOM element involved in the event, if any. For mouseout, it indicates the element being entered, and for mousein, it indicates the element being exited.
  • .which
    indicates the specific key or button that was pressed.
  • .pageX
    the x coordinate of the mouse cursor relative to the left edge of the page.
  • .pageY
    the y coordinate of the mouse cursor relative to the top edge of the page.
  • .result
    the last value returned by an event handler that was triggered by this event, unless the value was undefined.
  • .timeStamp
    returns the number of milliseconds since January 1, 1970 when the event is triggered.
  • .preventDefault()
    If this method is called, the default action of the event will not be triggered.
  • .stopPropagation()
    This method prevents the event from bubbling up the DOM tree looking for more event handlers to trigger.

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.

Using the event object in a handler looks like this:


$(document).ready(function() {/*from w  w w  . jav a2 s  .c o  m*/
 $('#foo').bind('click', function(event) {
    alert('The mouse cursor is at ('+ event.pageX + ', ' + event.pageY + ')');
 });
});

Passing event data

The optional eventData parameter allows us to pass additional information to the handler.


var message = 'hi!';
$('#foo').bind('click', {msg: message}, function(event) {
    alert(event.data.msg);/*from w  ww. java 2s . co  m*/
});
message = 'test!';
$('#bar').bind('click', {msg: message}, function(event) {
    alert(event.data.msg);
});

We can also add some extra data before the event handler


function handler(event) {
  alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)




















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities