Events
An event is something that happens on the page: a click, a key press, the mouse moving over an element, a form being submitted, the page finishing loading. Interactive pages are built by listening for events and running code when they happen. That code is called an event handler.
Your first handler
<button id="hello">Say hello</button>
<p id="out"></p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
let count = 0;
$("#hello").on("click", function () {
count++;
$("#out").text("Hello! You clicked " + count + " time(s).");
console.log("clicked", count);
});
</script>clicked 1
clicked 2.on(eventName, handler) attaches the handler to every selected element. The handler runs each time the event happens, not just once. The function is passed without parentheses; jQuery calls it later.
Which element was it?
When several elements share one handler, you need to know which one fired. Inside a normal function, this is that element:
<div>
<button data-colour="tomato">Tomato</button>
<button data-colour="seagreen">Sea green</button>
<button data-colour="slateblue">Slate blue</button>
</div>
<p id="swatch" style="padding: 12px">Pick a colour</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("button").on("click", function () {
const colour = $(this).data("colour");
$("#swatch").css("background", colour).text("You picked " + $(this).text());
console.log(colour);
});
</script>seagreenthis is a plain DOM element, so wrap it as $(this) to use jQuery methods. With an arrow function, this is not the element; use the event object's currentTarget instead (next lesson).
Named handlers
For anything longer than a line or two, give the handler a name. It is easier to read, test and reuse:
function addToCart() {
const id = $(this).data("productId");
console.log("adding", id);
}
$(".add-to-cart").on("click", addToCart);Make sure you pass addToCart, not addToCart(). With the parentheses, the function runs once, immediately, and its return value (usually undefined) is what gets attached.
Several events at once
Separate event names with spaces to share a handler, or pass an object to attach different handlers in one call:
<div id="card" tabindex="0" style="padding: 12px; border: 2px solid #cbd5e1">Hover, focus or click me</div>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#card").on("mouseenter focus", function (event) {
$(this).css("border-color", "#2563eb");
console.log("highlight on", event.type);
});
$("#card").on({
mouseleave: function () { $(this).css("border-color", "#cbd5e1"); },
click: function () { console.log("card clicked"); }
});
</script>highlight on mouseenter
card clickedevent.type tells you which of the events fired.
Common events
| Event | Fires when |
|---|---|
click, dblclick |
an element is clicked or double-clicked (also by keyboard on buttons and links) |
mouseenter, mouseleave |
the pointer moves onto or off an element |
keydown, keyup |
a key is pressed or released |
input |
the value of a field changes as the user types |
change |
a field's value is committed (select changed, checkbox ticked, text field left) |
focus, blur |
an element gains or loses keyboard focus |
submit |
a form is submitted |
scroll, resize |
the page or an element scrolls; the window is resized |
The lessons that follow look at mouse, keyboard and form events in detail.
Handlers attach to elements that exist now
.on() attaches handlers to the elements selected at that moment. Elements added later do not get them:
<ul id="list"><li>Existing item</li></ul>
<button id="add">Add item</button>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#list li").on("click", function () {
console.log("clicked:", $(this).text());
});
$("#add").on("click", function () {
$("#list").append("<li>New item</li>");
console.log("added a new item");
});
</script>added a new itemClicking the new item printed nothing. The fix is event delegation, which has its own lesson in this section.
Shorthand methods
Older code often uses shorthand methods named after events:
$("#save").click(function () { /* ... */ });
$("#name").keyup(function () { /* ... */ });
$(".card").hover(over, out);They still work in jQuery 4, but they are deprecated: the jQuery team recommends .on() for all new code, because it is one consistent method that also supports delegation, namespaces and several events at once. The same name with no arguments, such as .click(), triggers the event instead of listening for it, which is another reason to prefer .on("click", ...) and .trigger("click").
Common mistakes
- Calling the handler while attaching it:
.on("click", save()). - Using
thisin an arrow function handler. - Attaching handlers before the elements exist, for example in the head without document ready.
- Attaching the same handler twice (for example, inside another handler that runs repeatedly), so it runs twice per click. The
.off()lesson shows how to avoid it.
Exercise
Make three buttons labelled +1, +5 and +10 with a data-step attribute, and a counter shown in a paragraph. One shared handler should add the button's step to the counter.
Show one possible answer
<div><button data-step="1">+1</button><button data-step="5">+5</button><button data-step="10">+10</button></div>
<p id="count">0</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
let total = 0;
$("button").on("click", function () {
total += $(this).data("step");
$("#count").text(total);
console.log(total);
});
</script>5
15Key points
- $(selector).on("click", handler) runs the handler each time any selected element is clicked.
- Inside a normal function handler, this is the element that the event is for; wrap it as $(this).
- One .on() call can attach the same handler to several events ("mouseenter focus") or different handlers with an object.
- Shorthands such as .click(fn) still work in jQuery 4 but are deprecated; write .on("click", fn).