jQuery Events

Event Handlers and the Event Object

.on(events, [selector], [data], handler) replaces .bind(), .delegate() and shorthands such as .click(fn). With a selector it delegates to present and future children (Delegation and Batching). .one() fires once, .off() removes handlers, and namespaces (click.menu) let you remove only your own. .trigger(type, args) runs handlers and the default action; .triggerHandler() skips the default action and bubbling. The jQuery 561 event wraps the native one (e.originalEvent) and adds e.data, e.delegateTarget and e.result (the previous handler's return value). Returning false calls both preventDefault() and stopPropagation().

Delegation, namespaces, event data and trigger argumentsHTMLLive
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<ul id="menu"></ul>
<pre id="log" style="margin:0"></pre>
<script>
  const log = (msg) => $('#log').append(document.createTextNode(`${msg}\n`));
  $('#menu').on('click.menu', 'li', { shop: 'Lamps' }, function (e, via = 'user') {
    log(`${$(this).text()} in ${e.data.shop}, holder #${e.delegateTarget.id}, via ${via}`);
    return 42;
  }).on('click.menu', 'li', (e) => log(`previous handler returned ${e.result}`))
    .append('<li>Desk lamp</li>'); // added after binding: delegation still works
  $('#menu li').trigger('click', ['trigger()']);
  $('#menu').off('.menu').find('li').trigger('click'); // no handler runs
</script>
Browser output of Listing 8.65
Browser output of 65

jQuery 4 fires focus events in the standard order (blur, focusout, focus, focusin), which can break code tuned to the old sequence.