Skip to the content.

$.fn.on(events, selector?, data?, callback)

Bind one or more event handlers to every element in the collection. Supports a single event name, a space-separated list, or a plain object mapping events to handlers, with optional event delegation and per-binding data.

A handler may return false to call preventDefault() and stopPropagation() on the event. Inside the handler, this references the element the handler is currently being invoked on (the matched delegate when delegating, otherwise the bound element).

Signatures

on(events: EventMap): this;
on(events: string, callback: OnCallback): this;
on(events: string, selector: string, callback: OnCallback): this;
on(events: string, selector: string, data: unknown, callback: OnCallback): this;

one(events: EventMap): this;
one(events: string, callback: OnCallback): this;
one(events: string, selector: string, callback: OnCallback): this;
one(events: string, selector: string, data: unknown, callback: OnCallback): this;

OnCallback is (this: Element, event: Event, ...args: unknown[]) => void | false. EventMap is Record<string, OnCallback>.

Parameters

Returns

The original Dabby collection, for chaining.

Examples

import $ from "dabbyjs";
import "dabbyjs/events/on/on";

// Simple click handler
$("a").on("click", function (event) {
    event.preventDefault();
    console.log("link clicked", this.href);
});
import $ from "dabbyjs";
import "dabbyjs/events/on/on";

// Multiple events sharing one handler
$("input").on("focus blur", function (event) {
    this.classList.toggle("focused", event.type === "focus");
});

// Multi-event handler object
$("button").on({
    mouseenter() { this.classList.add("hover"); },
    mouseleave() { this.classList.remove("hover"); },
    click()      { this.classList.add("clicked"); },
});
import $ from "dabbyjs";
import "dabbyjs/events/on/on";

// Delegation: one listener on the container handles all current and future buttons
$(".list").on("click", ".delete-button", function () {
    this.closest(".list-item")?.remove();
});

// Per-binding data exposed as event.data
$("#save").on("click", { role: "primary" }, (event) => {
    console.log((event as Event & { data: { role: string } }).data.role);
});
import $ from "dabbyjs";
import "dabbyjs/events/on/on";

// .one() detaches the handler after it fires once
$(".banner").one("click", function () {
    this.classList.add("dismissed");
});

See also

Differences from jQuery

Does not support the jQuery.Event wrapper; handlers receive native Event objects. When the data property of the underlying event is not writable (which can happen for some native events), the handler reads the value from event._data instead of event.data.