jQuery Events
An event is something that happens on the page: a click, a key press, the mouse entering an element, a form being submitted. jQuery lets you attach a handler — a function that runs when the event happens — to any number of elements with one call.
Attaching handlers with .on()
.on(eventName, handler) is the main method. It works for every event type:
$("button").on("click", function () {
$(this).text("Clicked!");
});Inside the handler, this is the DOM element that received the event; wrap it as $(this) to use jQuery methods on it.
There are also shorthand methods like .click(fn), .dblclick(fn), .hover(fnIn, fnOut) and .keyup(fn). They still work in jQuery 3.7 but are deprecated since 3.3 in favour of .on().
Common events
| Category | Events |
|---|---|
| Mouse | click, dblclick, mouseenter, mouseleave, mousedown, mouseup, mousemove |
| Keyboard | keydown, keyup |
| Form | input, change, focus, blur, submit |
| Document/window | resize, scroll (on $(window)) |
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
.box { display: inline-block; width: 90px; height: 60px; margin: 4px; line-height: 60px;
text-align: center; background: #ddd; border-radius: 6px; user-select: none; }
.box.over { background: #0769ad; color: #fff; }
</style>
</head>
<body>
<div class="box" id="a">click</div>
<div class="box" id="b">dblclick</div>
<div class="box" id="c">hover</div>
<p>Type: <input id="field"> <span id="echo"></span></p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
let clicks = 0;
$("#a").on("click", function () {
clicks++;
$(this).text("clicks: " + clicks);
});
$("#b").on("dblclick", function () {
$(this).css("background", "gold");
console.log("double click!");
});
$("#c").on("mouseenter", function () {
$(this).addClass("over");
}).on("mouseleave", function () {
$(this).removeClass("over");
});
$("#field").on("input", function () {
$("#echo").text($(this).val().length + " chars");
});
</script>
</body>
</html>The event object
jQuery passes an event object to your handler. It is a normalised wrapper around the browser event.
| Property / method | Meaning |
|---|---|
e.type |
Event name, e.g. "click" |
e.target |
The element where the event started (may be a child) |
e.currentTarget |
The element the handler is attached to (same as this) |
e.which / e.key |
Mouse button / key that was pressed |
e.pageX, e.pageY |
Mouse position relative to the document |
e.preventDefault() |
Stop the browser's default action (following a link, submitting a form) |
e.stopPropagation() |
Stop the event bubbling up to parent elements |
e.originalEvent |
The raw browser event |
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif">
<a href="https://example.com" id="link">This link will not navigate</a>
<div id="pad" style="margin-top:12px;width:240px;height:110px;background:#eef5fb;border:1px solid #0769ad">
Move the mouse or press a key here
</div>
<p id="info">—</p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#link").on("click", function (e) {
e.preventDefault();
console.log("default action prevented for", e.type);
});
$("#pad").attr("tabindex", 0)
.on("mousemove", function (e) {
const off = $(this).offset();
$("#info").text("x: " + Math.round(e.pageX - off.left) + ", y: " + Math.round(e.pageY - off.top));
})
.on("keydown", function (e) {
console.log("key:", e.key);
});
</script>
</body>
</html>More ways to use .on()
// several events, one handler
$("#field").on("focus blur", function (e) {
$(this).toggleClass("active", e.type === "focus");
});
// an object of handlers
$("#card").on({
mouseenter() { $(this).addClass("lift"); },
mouseleave() { $(this).removeClass("lift"); }
});
// pass extra data to the handler
$("#save").on("click", { mode: "draft" }, function (e) {
console.log(e.data.mode); // "draft"
});Removing and one-time handlers
| Method | What it does |
|---|---|
.on(events, fn) |
Attach a handler |
.off(events, fn) |
Remove that handler (.off("click") removes all click handlers) |
.one(events, fn) |
Handler that runs only the first time, then removes itself |
.trigger("click") |
Fire the event (and its handlers) from code |
.on("click.myApp", fn) |
Namespaced event — remove just yours with .off(".myApp") |
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif">
<button id="once">Claim bonus (once)</button>
<button id="toggle">Start counting</button>
<button id="target">Count me</button>
<p id="out">0</p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#once").one("click", function () {
$(this).text("Bonus claimed").prop("disabled", true);
console.log("bonus handler ran");
});
let n = 0, on = false;
function count() { $("#out").text(++n); }
$("#toggle").on("click", function () {
on = !on;
if (on) $("#target").on("click.counter", count);
else $("#target").off("click.counter");
$(this).text(on ? "Stop counting" : "Start counting");
});
// fire a click from code
$("#toggle").trigger("click");
</script>
</body>
</html>Tip: For elements that are added to the page later, attach the handler to a parent with a selector —
$("#list").on("click", "li", fn). This is called event delegation and has its own lesson.
Test yourself
Inside a jQuery event handler, what is this?
- The jQuery object
- The DOM element the handler is attached to
- The window
- The event object
Which call stops a link from navigating when clicked?
e.stopPropagation()return truee.preventDefault()$(this).off()
Which method attaches a handler that runs only once?
.once().one().single().on("click", fn, 1)