jQuerybeginner 7 min
Run code when the user clicks, types or hovers, using on().
How to react to clicks and other user actions with .on(), and how to read what the user typed.
Pages become interactive when code responds to what people do: buttons, forms, menus and keyboard shortcuts.
An event is something that happens: a click, a key press, the mouse entering an element. You attach a handler, a function that runs when it happens:
Useful events: click, dblclick, mouseenter, mouseleave, keyup, change, submit.
Inside a handler, $(this) is the element that triggered it. For inputs, .val() reads or sets the value.
clicks starts at 0 and lives outside the handler, so it remembers its value.$(this).val() reads the current text in the input, which is displayed in #hello.Add a second button that resets clicks to 0 and updates the text.
$(function () { ... })..on("click", doIt()) runs immediately.this. In handlers that use $(this), use a normal function..on("event", handler) runs code when something happens.$(this) is the element that fired the event; .val() reads form values.Next: effects and animation.
$("#btn").on("click", function () {
// runs on every click
});<button id="btn">Click me</button>
<p id="out">Clicks: 0</p>
<input id="name" placeholder="Type your name">
<p id="hello"></p>
<script>
$(function () {
let clicks = 0;
$("#btn").on("click", function () {
clicks++;
$("#out").text("Clicks: " + clicks);
});
$("#name").on("keyup", function () {
$("#hello").text("Hello, " + $(this).val());
});
});
</script>