Skip to the content.

Named event shortcuts

This module installs twenty-four shortcut methods on Dabby.prototype, one per common DOM event. Each method has a dual behaviour: when called with no arguments it triggers the event on every element in the collection (equivalent to .trigger("eventName")); when called with a callback (and optionally a delegation selector and per-binding data) it binds a handler (equivalent to .on("eventName", ...)).

Importing this module pulls in .on() and .trigger() automatically.

Signatures

Every shortcut shares the same four overloads. The signature for click is shown — substitute any of the available method names listed below.

click(): this;
click(callback: OnCallback): this;
click(selector: string, callback: OnCallback): this;
click(selector: string, data: unknown, callback: OnCallback): this;

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

Parameters

When invoked with no arguments, the method instead triggers the event and takes no parameters.

Returns

The original Dabby collection, for chaining.

Available methods

Mouse events

Keyboard events

Focus events

Form events

Window and document events

Examples

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

// Bind a click handler
$("#save").click(function (event) {
    event.preventDefault();
    saveDocument();
});

// Trigger the click programmatically
$("#save").click();

declare function saveDocument(): void;
import $ from "dabbyjs";
import "dabbyjs/events/named/named";

// Delegated handler — one listener for many descendants
$(".list").click(".delete-button", function () {
    this.closest(".list-item")?.remove();
});

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

// Inside a handler, `this` is the matched element
$("input").focus(function () {
    this.classList.add("focused");
}).blur(function () {
    this.classList.remove("focused");
});

// Replace a broken image with a placeholder
$("img").error(function () {
    (this as HTMLImageElement).src = "/images/placeholder.png";
});
import $ from "dabbyjs";
import "dabbyjs/events/named/named";

// Window-level shortcuts
$(window).resize(() => {
    document.body.classList.toggle("narrow", window.innerWidth < 768);
});

$(window).scroll(function () {
    const scrolled = (this as unknown as Window).scrollY > 100;
    document.body.classList.toggle("scrolled", scrolled);
});

See also

Differences from jQuery

None.