The jQuery API method of .on() attaches event handlers to the selected set of matched elements and allows you to attach functions. 

The .on() method can replace other event handlers such as .bind(), .delegate() and .live().

To remove events bound with .on(), use the jQuery API method of .off().


The syntax for the jQuery API .on() event

The event type is required as is the handler. A selector and passed data is optional.

$("selector").on(event, [selector,] [data,] handler)

$("#identityForm").on("keydown", "input", function (event) {
    // code goes here

In this example, the selector is the element with id="indentityForm. The event is "keydown". The optional selector is "input" and the handler is the function().


Event names

Any event names can be used with the .on() method. Coomon events are things like click, change, focus, keypress, keyup, mouseenter, mouseleave, etc.

A list of JavaScript events can be found at:

Event handlers are bound to the currently selected elements. These elements must exist on the page when the .on() method comes into call. If you are using AJAX to bring in additional elements, you should place the .on() method after the AJAX is performed if the .on() method has selectors that are only present in the additional HTML. 

Event handlers

For the event handler, you can have a function() included or you can call a function that is defined elsewhere.

$('#startButton').on('click', function () {
    // code goes here


$('#startButton').on('click', runProgram);

where runProgram is a function that has been defined elsewhere.


An example of the jQuery .on( ) method

This is a very simple example of how to use the .on() method. In this example, the event is "click" and the handler is a function that loads html into the element selected.

    $(this).html("<img src='images/clock.png' alt='Illustration of a clock'>");

 Here is the HTML for this example:

<div id="imageDisplay"></div>
<p>Click on the box to the left to see the jQuery API method of .on() in action.</p>

Here is the result: