JavaScript Event Object — Explained with Examples

Understand where the event object comes from, what it contains, and how it works in real-time.

1. What is the Event Object?

In JavaScript, every time something happens on a webpage — like a click, keypress, or form submit — the browser automatically creates an Event Object. This object stores all details about that event, such as:

You don’t create this object yourself — the browser provides it automatically and passes it to your event handler.

2. Example: Click Event

<button id="btn">Click Me</button>

<script>
const btn = document.getElementById("btn");

btn.addEventListener("click", function(event) {
  console.log(event.type);     // "click"
  console.log(event.target);   // <button id="btn">
  console.log(event.clientX);  // Mouse X position
});
</script>

🎯 Try It:

3. Example: Keyboard Event

When you type inside the input box, the browser creates a KeyboardEvent and provides details like which key was pressed.

<input type="text" id="keyInput" placeholder="Type here...">

<script>
document.getElementById("keyInput").addEventListener("keydown", function(e) {
  console.log("Key:", e.key);
  console.log("Code:", e.code);
});
</script>

⌨️ Try Typing:

4. How the Event Object Originates

The Event Object originates from the browser’s DOM event system. Every time you interact with the page:

  1. The browser detects the event (click, scroll, etc.).
  2. The DOM’s internal EventTarget interface creates an event object (like MouseEvent).
  3. The browser then calls your JavaScript handler and passes this object as the first argument.

In short, the event object is born inside the browser, not JavaScript itself.

5. Event Object Types

Different events produce different types of event objects:

Event Type Object Type Example Properties
Click / Mouse MoveMouseEventclientX, clientY, button
Key PressKeyboardEventkey, code, ctrlKey
Form SubmitSubmitEventtarget, type
Scroll / ResizeUIEventview, detail
Custom EventsCustomEventdetail

6. Using event.preventDefault()

You can use event.preventDefault() to stop the browser's default action — like preventing a form from submitting or a link from navigating.

<form id="demoForm">
  <input type="text" placeholder="Enter name">
  <button type="submit">Submit</button>
</form>

<script>
document.getElementById("demoForm").addEventListener("submit", function(event) {
  event.preventDefault(); // stop form reload
  alert("Form submission stopped by event.preventDefault()");
});
</script>

🧾 Demo Form: