jQuery Event Handling

Event Handling

  1. .click(handler) - event handling for specified elements
$("your_selector").click(function(event) {
// do something
});
  1. .on( events [, selector ] [, data ], handler ) - event handling for dynamic elements
$(document).on("click","your_selector", function (event) {
// do something
});

if you know the particular node you’re adding dynamic elements to, you could specify it instead of the document.

$("parent_selector").on("click","your_selector", function (event) {
// do something
});

Passing data to the handler

$(document).on("click", "#your_div", {name: "Jack"}, handler);

function handler(event){
console.log(event.data.name);
}

Deprecated API

As of jQuery 3.0, .bind() and .delegate() have been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.

Get the element that triggered the event

$("your_selector").click(function(event) {
// get the element
console.log(event.target);
console.log(this);

// get the element id
console.log(this.id);
console.log(event.target.id);
console.log($(this).attr('id'));

// Get jQuery object by element
console.log($(this).html());
console.log($(event.target).html());
});

Get the element that triggered the event

  • event.target
  • this

Note: event.target equals this, and equals document.getElementById("your_selector")

Get the element id

  • this.id
  • event.target.id
  • $(this).attr('id')

Get jQuery object by element

  • $(this)
  • $(event.target)

jQuery Events

Form Events

  • .blur(handler)
  • .change(handler)
  • .focus(handler)
  • .focusin(handler)
  • .focusout(handler)
  • .select(handler)
  • .submit(handler)

Keyboard Events

  • .keydown(handler)
  • .keypress(handler)
  • .keyup(handler)

Mouse Events

  • .click(handler)
  • .contextmenu(handler). The contextmenu event is sent to an element when the right button of the mouse is clicked on it, but before the context menu is displayed.
  • .dblclick(handler). The dblclick event is sent to an element when the element is double-clicked.
  • .hover(handlerIn, handlerOut)
  • .mousedown(handler)
  • .mouseenter(handler)
  • .mouseleave(handler)
  • .mousemove(handler)
  • .mouseout(handler)
  • .mouseover(handler)
  • .mouseup(handler)
  • .toggle(handler, handler). Bind two or more handlers to the matched elements, to be executed on alternate clicks.