jQuery: The Write Less, Do More JavaScript Library

Events (Guide)

From jQuery JavaScript Library

Jump to: navigation, search

jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). So far it normalizes the target and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.

Things to do here: Normalize mouse/keyboard properties and document. Provide some more complex examples of the event system, and add links to the API methods.

Contents

event.type

Describes the nature of the event.

Return value: String
Example:

 $("a").click(function(event) {
  alert(event.type);
});
Result:
 "click"


event.target

Contains the DOM element that issued the event. This can be the element that registered for the event or a child of it.

Fixed where necessary (IE, Safari).

Use to implement event delegation.

Return value: Element
Example:

$("a[@href=http://google.com]").click(function(event) {
  alert(event.target.href);
});
Result:
"http://google.com"


Example:

Implements a simple event delegation: The click handler is added to an unordered list, and the children of it's li children are hidden. Clicking one of the li children toggles (see toggle()) their children.

function handler(event) {
  var target = $(event.target);
  if( target.is("li") ) {
    target.children().toggle();
  }
}
$("ul").click(handler).find("li > ").hide();


event.pageX/Y

The pageX/Y property pair returns the mouse coordinates relative to the document.

Fixed where necessary (IE).

Return value: String
Example:

$("a").click(function(event) {
  alert("Current mouse position: " + event.pageX + ", " + event.pageY );
});
Result:
"Current mouse position: 130, 640"


event.preventDefault( )

Prevents the browser from executing the default action.

Fixed where necessary (IE).

Return value: undefined

Example:

Stops the browser from changing the page to the href of any anchors.

$("a").click(function(event){
  event.preventDefault();
  // do something
});


event.stopPropagation( )

Stops the bubbling of an event, prohibiting other handlers to get to handle that event.

Fixed where necessary (IE).

Return value: undefined

Example:

Prohibits other event handlers to be called.

$("p").click(function(event){
  event.stopPropagation();
  // do something
});