The Event Object

Every handler receives an event object full of useful details.

Syntaxfunction (event) { /* use event here */ }

jQuery passes a normalized event object to every handler. It works the same across browsers.

Property / MethodMeaning
e.typethe event name (e.g. click)
e.targetthe actual element that fired it
e.pageX, e.pageYpointer coordinates
e.preventDefault()cancel the default action
e.stopPropagation()stop the event bubbling up

Example

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

When to use it

  • A context-menu script reads e.pageX and e.pageY from the event object to position a popup at the right-click location.
  • A form uses e.preventDefault() from the event object to stop submission and run client-side validation first.
  • A keyboard shortcut handler checks e.ctrlKey and e.key from the event object to trigger actions like save (Ctrl+S).

More examples

Prevent default link navigation

e.preventDefault() is called on the event object to stop the browser following the href.

Example · html
<a id="link" href="https://example.com">Click me</a>
<p id="log"></p>
<script>
$(function () {
  $("#link").on("click", function (e) {
    e.preventDefault();
    $("#log").text("Default navigation blocked.");
  });
});
</script>

Read mouse coordinates from event

e.pageX and e.pageY give the cursor position relative to the document on every mousemove.

Example · html
<div id="area" style="height:150px;background:#eef;cursor:crosshair;"></div>
<p id="coords"></p>
<script>
$(function () {
  $("#area").on("mousemove", function (e) {
    $("#coords").text("X: " + e.pageX + "  Y: " + e.pageY);
  });
});
</script>

Keyboard shortcut with modifier key

e.ctrlKey is a boolean on the event object that is true when Ctrl is held, enabling composite shortcuts.

Example · html
<p>Press Ctrl+S to "save"</p>
<p id="saved"></p>
<script>
$(function () {
  $(document).on("keydown", function (e) {
    if (e.ctrlKey && e.key === "s") {
      e.preventDefault();
      $("#saved").text("Document saved at " + new Date().toLocaleTimeString());
    }
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.