Documentation

Types/Event

From jQuery JavaScript Library

Jump to: navigation, search

Below documented are all properties of an event object. It is mentioned where jQuery helps to make them available cross-browser.

Contents

type

The nature of the event, like "click", "mouseup" or "blur".

$("a").click(function(event) {
  console.log(event.type); // "click"
});

target

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).

$("a[href='http://google.com']").click(function(event) {
   console.log(event.target.href); // "http://google.com"
});

The target property is the key to implement event delegation. Event delegation is very useful when dealing with a large amount of elements that all need the same event handling. By applying the event handler to the parent element, only a single event handler is created.

In the following example, 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 their children.

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

relatedTarget

On mouseout, the relatedTarget is the element the mouse is moving *into*. On mouseover, the relatedTarget is the element the mouse is moving *away from*.

jQuery uses relatedTarget to implement it's hover method.

pageX, pageY

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

Fixed where necessary (IE).

$("a").click(function(event) {
  // "Mouse position: 321, 450"
  console.log("Mouse position: " + event.pageX + ", " + event.pageY );
});

event.preventDefault()

Prevents the browser from executing the default action.

Fixed where necessary (IE).

$("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).

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

which

On mouse events:

* 1 is left
* 2 is middle
* 3 is right
// Remember to use onmouse* events to access these values.

On keypress:

* is the ASCII value of the key pressed
* takes into consideration capital or lowercase letters

On other key events:

* it's not very useful
* use keyCode (which returns the upper-case version of the key pressed)
* keyChar is pretty much useless, so you can't get the true ASCII value
  except using which on keypress

metaKey

Is the apple-key on OSX browsers and the control-key on other operating systems. This allows you to produce expected OS-specific behavior (such as meta-B for bold).