Skip to content
jQuery

Events & Delegation

Bind handlers with on(), support delegation and namespaced removal.

By EZ4Code Team
eventsdelegation

Code

// Click handler
$("#btn").on("click", function (e) {
  console.log("clicked", this);
});

// Multiple events
$("#box").on({
  mouseenter: () => console.log("enter"),
  mouseleave: () => console.log("leave")
});

// Event delegation (handles dynamically added children)
$("#list").on("click", "li.item", function () {
  $(this).toggleClass("selected");
});

// One-time event and namespaced removal
$("#once").one("click", () => alert("once"));
$(document).off("click.myApp");

Explanation

on() binds one or more handlers to elements, supporting event delegation by passing a child selector. Delegation lets handlers fire for elements added later. The one() method auto-unbinds after a single trigger, and namespaces (.myApp) allow targeted cleanup.

More jQuery Snippets