.on(events ,selector ,data ,$)

Description: Attach the jQuery chain behind to one or more events.

events – string
One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
selector – string, optional
A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
data – object, optional
A map of data that will be passed to the event handler.
$ – the jQuery token, optional
Use $ instead of a handler or leave it out.

Tip: Many other methods that internally call .on() and pass the handler function will automatically support that timing, too:
.click($), .dblclick($), .mousedown($), .mouseup($), .mousemove($), .keydown($), etc…

Usage pattern


Examples with timed version of .on()

Example #3: a simple inline click handler

The handler-less version of .on() allows to create small event handlers very easily. In this example the span element is shifted right with each button click.


Watch me moving!

Example #4: blinking a given number of times on click

We repeat .toggleClass() for an even number of times, so the class "blink" is absent again when the repeat loop finishes.

Remark that the click handler is assigned directly in the invocation chain using .click($).

$('.example button').click($).siblings('span')

Example #10: fading submenus with user friendly timeouts

Menu navigation is frustrating when the submenu closes immediately on mouseleave, because sometimes the mouse pointer moves few pixels unintended. That's why we want to build in timeouts on mouseenter and mouseleave to show/hide the corresponding submenu.

With jquery-timing this is just two lines:

$('#menu li')

Example #13: quick image selection

In this example the user can choose an image by clicking on it. He can change his choice as often as he wants.

The "ready" button will always disable if last image is unselected.

Choose your preferred image:
  • Spaghetti Bolognese
  • Spaghetti Carbonara
  • Tortellini
  • Shrimps
  • Cake
  • Sweets
  • Coffee

Example #18: falling little boxes

This example first creates 25 little boxes with an inline definition:

These 25 boxes shall be animated as falling down with each button click.

A helper function is necessary to animate them in reverse order:
$.fn.reverse = function() {
  return this.$(this.get().reverse());

Try clicking on that button multiple times during animation. With .stop(true,true) and .unwait() all animations are reset at the beginning.

  .$('#boxparent div').stop(true,true).unwait()