SyntaxStudy
Sign Up
jQuery Advanced Event Handling
jQuery Intermediate 10 min read

Advanced Event Handling

Advanced jQuery Event Handling

Namespaced Events

// Bind with namespace
$("button").on("click.myPlugin", function() { ... });

// Remove only that namespace
$("button").off("click.myPlugin");

One-Time Events

$("button").one("click", function() {
    console.log("Fires only once");
});

Trigger Events

$("form").trigger("submit");
$("input").trigger("focus");

// Custom event
$("div").on("myEvent", function(e, data) {
    console.log(data);
});
$("div").trigger("myEvent", ["Hello!"]);

Event Object

$("a").on("click", function(e) {
    e.preventDefault();    // stop default action
    e.stopPropagation();   // stop bubbling
    console.log(e.target, e.currentTarget);
    console.log(e.pageX, e.pageY);  // mouse position
});
Pro Tip

Namespace your events when building plugins so they can be removed without affecting other handlers.