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() {/*  ww w  .ja  v a 2  s  . c  om*/
 $('#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);//w w w . j a va 2  s  .c  om
});
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 »
  Javascript Tutorial »
    jQuery Reference »
      Event
Javascript Tutorial Event
Event
Event attributes
event.keycode
event.clientX/clientY
pageX/pageY
Cancel event
Event target
bind
.blur()
.change()
.click()
.error()
.dblclick()
.delegate()
.die()
.focus()
.hover()
.keydown()
.keypress()
.keyup()
.live()
.load()
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseover()
.mouseout()
.mouseup()
.off()
.on()
.one()
.ready()
.resize()
.scroll()
.select()
.submit()
.toggle()
.trigger()
.triggerHandler()
.unbind()
.undelegate()
.unload()