Core Features

Events

Handle user interactions with jQuery's powerful and convenient event system.

Attaching Event Handlers

The .on() method is the recommended way to attach event listeners. It also works for dynamically added elements.

Common Events

  • click — mouse click
  • submit — form submission
  • keyup / keydown / keypress — keyboard events
  • mouseenter / mouseleave — hover (no bubbling)
  • change — input value changes
  • focus / blur — element gains/loses focus
  • scroll / resize — window events

Event Object

Event handlers receive an event object with useful properties: event.target, event.type, event.preventDefault(), event.stopPropagation()

Example

javascript
// Basic click handler
$("button").on("click", function() {
  alert("Button clicked!");
});

// Using this to reference clicked element
$(".btn").on("click", function() {
  $(this).toggleClass("active");
  console.log("Clicked:", $(this).text());
});

// Prevent default behavior
$("a.no-navigate").on("click", function(e) {
  e.preventDefault();
  console.log("Link click intercepted");
});

// Form submission
$("form").on("submit", function(e) {
  e.preventDefault();
  const name = $("#name").val();
  const email = $("#email").val();
  console.log("Submitted:", { name, email });
});

// Delegated events (for dynamic elements)
// Attaches to .list, triggers when .item inside it is clicked
$(".list").on("click", ".item", function() {
  $(this).remove();
});

// Multiple events
$("input").on("focus blur", function(e) {
  $(this).toggleClass("focused", e.type === "focus");
});

// Keyboard events
$(document).on("keydown", function(e) {
  if (e.key === "Escape") $(".modal").hide();
  if (e.ctrlKey && e.key === "s") {
    e.preventDefault();
    saveDocument();
  }
});

// Removing event handlers
$("button").off("click");
$(".item").off("mouseenter mouseleave");
Try it yourself — JAVASCRIPT