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 clicksubmit— form submissionkeyup/keydown/keypress— keyboard eventsmouseenter/mouseleave— hover (no bubbling)change— input value changesfocus/blur— element gains/loses focusscroll/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");
// None of the handlers above are attached to anything: .on() binds to elements
// that exist AT THE TIME IT RUNS, and this page starts blank. That is why the
// panel printed nothing. Build a DOM, bind to it, then fire the events:
$("#demo").css({ background: "#fff", color: "#1a1a1a", padding: "1rem" });
$("#demo").append(
'<button id="go">Click me</button>' +
'<ul class="list"><li class="item">Item A</li><li class="item">Item B</li></ul>'
);
$("#go").on("click", function () {
console.log("clicked:", $(this).text());
});
// Delegation: the handler lives on the list, not on the items, so it also
// covers items added later.
$(".list").on("click", ".item", function () {
console.log("removing:", $(this).text());
$(this).remove();
});
$("#go").trigger("click");
$(".list .item:first").trigger("click");
console.log("items left:", $(".list .item").length);Try it yourself — JAVASCRIPT