jQuery Events

A static page is not very useful on its own. Events are how a page responds to the person using it, whether that is a click, a keypress, or the mouse moving across a menu. jQuery gives you a clean, consistent way to listen for these events and run your own code when they happen.

What is an event?

An event is something that happens in the browser: a button is clicked, a form is submitted, a key is pressed, or the page finishes loading. jQuery lets you attach a function, called an event handler, that runs automatically the moment that event occurs on the elements you selected.

The pattern mirrors everything else in jQuery. You select the elements, then call an event method and pass it a function. That function is your handler, and jQuery calls it for you at the right time.

Attaching your first event handler

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<button id="myButton">Click me</button>
<p>Move the mouse over this paragraph.</p>

<script>
// Run code when the button is clicked
$("#myButton").click(function() {
  alert("You clicked the button!");
});

// Hide a paragraph when the mouse enters it
$("p").mouseenter(function() {
  $(this).hide();
});
</script>

</body>
</html>

The document ready event

You should wait until the page is fully loaded before wiring up events, otherwise your code might try to attach a handler to an element that does not exist yet. jQuery solves this with the ready event, which fires as soon as the HTML is in place.

Waiting for the page to be ready

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<button id="greet">Click me</button>

<script>
$(document).ready(function() {
  // Safe to work with any element now
  $("#greet").click(function() {
    $(this).text("Hello!");
  });
});

// Shorthand for the same thing
$(function() {
  $("#greet").click(function() {
    $(this).text("Hello!");
  });
});
</script>

</body>
</html>

Common events at a glance

MethodFires whenTypical use
click()The element is clickedButtons, links, toggles
dblclick()The element is double-clickedQuick edit or expand actions
mouseenter()The pointer moves onto the elementHover highlights
mouseleave()The pointer moves off the elementResetting a hover state
keydown()A key is pressed downKeyboard shortcuts
keyup()A key is releasedLive search, validation
focus()An input gains focusHighlighting the active field
blur()An input loses focusValidating a field on exit
submit()A form is submittedChecking data before sending
hover()Pointer enters and leavesTwo handlers in one call

The event object and this

Inside a handler, the keyword this refers to the specific element that triggered the event, so $(this) lets you act on just that element. jQuery also passes an event object to your function, giving you details such as which key was pressed or where the mouse was, plus methods like preventDefault() to stop the browser's default behavior.

Using the event object

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<a href="https://example.com">Example link</a>
<br>
<input type="text" id="name" placeholder="Type your name">

<script>
// Stop a link from navigating away
$("a").click(function(event) {
  event.preventDefault();
  console.log("Link click was blocked");
});

// The on() method attaches any event by name
$("#name").on("keyup", function() {
  console.log("Current value: " + $(this).val());
});
</script>

</body>
</html>
  • Use the on() method when you want one flexible way to attach any event, or to attach several events at once.
  • $(this) inside a handler targets only the element that fired the event, which is handy when many elements share the same handler.
  • Call event.preventDefault() to stop default actions like a link navigating or a form submitting.
  • Call event.stopPropagation() to keep the event from bubbling up to parent elements.
Note: The on() method is the modern, preferred way to bind events. Shortcuts like click() and mouseenter() are convenient, but on() also supports event delegation, letting you handle events for elements that get added to the page later.
Note: Attaching the same handler repeatedly, for example inside code that runs more than once, can bind it multiple times and make it fire twice. If you need to be safe, call .off() to remove existing handlers before adding a new one.

Exercise: jQuery Events

Which jQuery method is the modern, general-purpose way to attach an event handler?