The on() Method

Attach one or many event handlers with the flexible on() method.

Syntax$(selector).on("event", handler);

.on() is the all-purpose way to bind events in modern jQuery. It replaces older shortcuts like .click() and .hover().

Handle several events at once

$("#box").on("mouseenter mouseleave", function (e) {
  $(this).toggleClass("hot");
});

Or pass an object of events

$("#box").on({
  click:      function () { /* ... */ },
  mouseenter: function () { /* ... */ }
});

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A search box uses .on("input") to filter a list in real time as the user types.
  • A toolbar button handles both click and touchstart with a single .on("click touchstart") call.
  • An analytics module attaches custom event listeners via .on() for internally triggered synthetic events.

More examples

Attach a single event with on()

.on("click", handler) is the recommended way to attach event handlers; equivalent to .click(handler).

Example · html
<button id="saveBtn">Save</button>
<p id="status"></p>
<script>
$(function () {
  $("#saveBtn").on("click", function () {
    $("#status").text("Saved successfully!");
  });
});
</script>

Bind multiple events at once

Passing a space-separated string to .on() binds multiple event types to the same handler function.

Example · html
<input id="search" type="text" placeholder="Type to search..." />
<p id="hint"></p>
<script>
$(function () {
  $("#search").on("focus blur", function (e) {
    $("#hint").text(e.type === "focus" ? "Start typing..." : "");
  });
});
</script>

Bind multiple events with a map

Passing an object to .on() maps multiple event types to separate handlers in one readable block.

Example · html
<div id="box" style="width:100px;height:100px;background:#4caf50;"></div>
<p id="log"></p>
<script>
$(function () {
  $("#box").on({
    mouseenter: function () { $("#log").text("Entered"); },
    mouseleave: function () { $("#log").text("Left"); },
    click:      function () { $("#log").text("Clicked"); }
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.