Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 56 ยท Events

Mouse, Keyboard and Form Events

A practical tour of jQuery's most used events: click, dblclick, mouseenter, keydown, input, change, focusin, resize and scroll, with throttling for busy events.

Browsers fire dozens of event types, but day-to-day jQuery work revolves around a short list. Knowing exactly which event to pick, and what each one does and does not tell you, saves a lot of confusing bugs: handlers that fire twice, validation that runs too late, scroll code that makes the page stutter.

This lesson walks through the mouse, keyboard, form, window and scroll events you will use most. It assumes you can attach handlers with .on() and read the event object.

The events you will use most

Mouse click, dblclick, mouseenter, mouseleave, mousemove
Keyboard keydown and keyup
Forms input, change, submit, focusin, focusout
Window resize and scroll
1 / 2

Mouse events

click fires after a press and release on the same element, for the primary button. dblclick fires on a quick double click. Remember that a double click first produces two click events, so avoid giving the same element different jobs on click and dblclick.

For hover effects use mouseenter and mouseleave. They fire once when the pointer enters or leaves the element, regardless of its children. Their cousins mouseover and mouseout bubble, so moving between child elements triggers them again and again, which is rarely what you want for a simple hover.

JavaScript
$(".card").on("mouseenter mouseleave", function (event) {
  $(this).toggleClass("hover", event.type === "mouseenter");
});

jQuery also has a .hover(inFn, outFn) shorthand, but it simply wraps mouseenter and mouseleave. For purely visual hover styling, a CSS :hover rule is simpler and needs no script.

mousemove fires continuously while the pointer moves, so keep its handler light.

Mouse events on a pad

Double-click once and watch: the click counter rises by two, the double-click counter by one.

Keyboard events

Use keydown when you want to react the moment a key goes down, including repeats while it is held, and for keys that do not produce characters (arrows, Escape, Enter). Use keyup when you want to act after the key has been released and the field already contains the new character.

keypress is deprecated and does not fire for many keys. Do not use it in new code.

JavaScript
$("#search").on("keydown", function (event) {
  if (event.key === "Escape") {
    $(this).val("");
  }
});

Remember that a keyboard event reports a key, not text. For anything about what the user typed into a field (including paste, drag-and-drop, autofill and mobile keyboards) use the input event instead.

Form events

input fires every time the value of a text field changes, however it changed. change fires when the value has been committed: for text fields that is when the field loses focus after being edited, and for checkboxes, radios and selects it fires immediately.

input versus change

The counter updates on every keystroke (input), while the "committed" line appears only after you leave the field (change).

focus, blur, focusin and focusout

focus and blur fire on the element itself and do not bubble. focusin and focusout do bubble, so they work when you want one handler on a form or container, as you saw in Event Delegation.

JavaScript
$("form").on("focusin", "input", function () { $(this).addClass("active"); });
$("form").on("focusout", "input", function () { $(this).removeClass("active"); });

For styling the focused field, CSS :focus-within and :focus-visible often remove the need for script entirely.

submit

The submit event belongs on the form, not on the submit button. That way it also runs when the user presses Enter inside a field. You will use it in Form Validation.

Window events: resize and scroll

resize fires on $(window) when the viewport changes size, and scroll fires on the window or on any scrollable element. Both can fire dozens of times per second, so putting heavy work inside them makes pages janky.

The fix is throttling: allow the handler to do real work at most once per interval. A minimal version is only a few lines.

JavaScript
function throttle(fn, wait) {
  var last = 0;
  return function () {
    var now = Date.now();
    if (now - last >= wait) {
      last = now;
      fn.apply(this, arguments);
    }
  };
}

$(window).on("scroll", throttle(function () {
  console.log($(window).scrollTop());
}, 100));

A related trick is debouncing: wait until the events stop for a moment, then run once. Debouncing suits search boxes and final window sizes; throttling suits continuous feedback such as a progress bar.

Throttling a busy event

The raw count climbs far faster than the throttled one. Wrapping a handler with throttle() is a straight swap, because it returns a normal function you hand to .on().

Namespace your window handlers ($(window).on("resize.layout", ...)) so a component can remove its own with .off(".layout"). Window handlers outlive the elements that created them.

Event method reference

jQuery has accumulated several ways to say "run this when that happens". New code needs .on() and .off(), but you will meet the others, so here is the whole family in one place.

Method What it does Use today?
.on(events, selector, fn) / .off() attach and remove handlers, with optional delegation yes, always
.one(events, fn) like .on(), but runs the handler once and removes it yes
.bind() / .unbind() the pre-1.7 names for .on() / .off() without delegation deprecated in 3.0
.delegate() / .undelegate() delegation with the selector first deprecated in 3.0
.live() / .die() delegation from document removed in 1.9
.click(fn), .focus(fn), .select(fn) and other shorthands .on("click", fn); with no argument they trigger the event fine for triggering, .on() preferred
.hover(inFn, outFn) binds mouseenter and mouseleave; with one function it runs for both works; mouseenter/mouseleave are clearer
.focusin() / .focusout() bubbling versions of focus / blur yes, for delegation
.resize(fn), .scroll(fn) window or element resize and scroll yes; throttle them
.select(fn) fires when text inside a text field or textarea is selected rarely needed
.load(fn) the event shorthand was removed in 3.0; .load(url) the AJAX loader is separate removed
.unload(fn) / .error(fn) removed in 3.0 use .on("unload") sparingly, and .on("error")

Three practical notes.

Shorthands are two things in one. $("#go").click(fn) binds, while $("#go").click() triggers a click and runs the handlers you bound. The same names behave this way for every shorthand. Triggering is described in Controlling Events.

.one() is handy for first-time-only logic, such as a tooltip you show on first focus or an intro animation. You can pass a delegation selector too, and the handler runs once per matching element, not once overall unless you also call .off().

.hover() with one function runs it on both enter and leave, so you check event.type to tell them apart, which is the same pattern as .on("mouseenter mouseleave", fn).

one, hover, select and the old bind/unbind

After the first click the .one() handler is gone, so the second click only runs the namespaced bind handler, and after unbind a third click does nothing. The last line prints undefined because no click handlers remain.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which event is best for updating a character counter as the user types or pastes?

    input fires on every value change, including paste and autofill. change fires only when the value is committed.
  2. 2. Why prefer mouseenter over mouseover for a simple hover effect?

    mouseover and mouseout bubble from children, causing repeated calls. mouseenter and mouseleave ignore movement between descendants.
  3. 3. A handler on the scroll event does heavy layout work and the page feels slow. What is a good fix?

    scroll can fire dozens of times per second. Throttling limits how often the expensive work runs.
  4. 4. Which event bubbles and is therefore suitable for delegating 'field gained focus'?

    focusin (and focusout) bubble, unlike focus and blur.
  5. 5. Where should a submit handler be attached?

    The form's submit event also fires when the user presses Enter in a field, which a button click handler would miss.

Summary

  • Use mouseenter/mouseleave for hover, click for activation, and remember a double click also produces two clicks.
  • keydown and keyup report keys (read event.key); keypress is deprecated.
  • input reacts to every edit; change reacts when the value is committed.
  • focusin and focusout bubble; focus and blur do not.
  • Attach submit to the form, not the button.
  • Throttle or debounce scroll, resize and mousemove handlers, and namespace window handlers so you can remove them.

Next, invent your own events and decouple your code with them in Custom Events and Pub/Sub.