4.2 Module 4 · Document Object Model (DOM)

Events Handling

Learn how JavaScript listens for user interactions — mouse clicks, keyboard input, form submissions — and executes code in response to make pages truly interactive.

1

Definition

Event handling in JavaScript is the process of detecting user interactions — such as clicks, keystrokes, or form submissions — and executing specific code in response. The code that runs is called an event handler or event listener.

Events are the bridge between the user and your JavaScript logic. Without event handling, a web page is a static document. With it, every button press, every keystroke, and every form submission can trigger a response.

2

Simple Way

Events are actions the user performs — JavaScript listens for them and reacts:

onclick User clicks a button, link, or any element
onkeydown User presses a key — fires the moment the key goes down
onkeyup User releases a key — fires after the key is let go
onsubmit User submits a form — use event.preventDefault() to stop the page reload
oninput The value of an input changes — fires on every character typed
3

Code Examples

Example 1 — Mouse Event (onclick)
<button onclick="handleClick()">Click Me</button>

<script>
  function handleClick() {
    console.log("Button was clicked!");
  }
</script>
Live Preview
Explanation
  • onclick is an inline event attribute — the simplest way to attach a handler
  • When the button is clicked, the browser calls handleClick() automatically
  • The function can do anything — update the page, call an API, show an alert
Example 2 — Keyboard Event (onkeyup)
<input type="text" onkeyup="handleKey(event)"
       placeholder="Start typing...">

<script>
  function handleKey(event) {
    console.log("Key released:", event.key);
    console.log("Current value:", event.target.value);
  }
</script>
Live Preview
Explanation
  • The event object is passed automatically — it contains details about what happened
  • event.key tells you which key was pressed ("Enter", "a", "Backspace" etc.)
  • event.target is the element that triggered the event — here the input field
Example 3 — Form Event & event.preventDefault()
<form onsubmit="handleSubmit(event)">
  <input id="nameField" type="text" placeholder="Your name">
  <button type="submit">Submit</button>
</form>

<p id="msg"></p>

<script>
  function handleSubmit(event) {
    event.preventDefault(); // stops the page from reloading

    let name = document.getElementById("nameField").value;
    document.getElementById("msg").textContent =
      "Hello, " + name + "!";
  }
</script>
Live Preview
Explanation
  • By default a form submission reloads the page — event.preventDefault() stops this
  • The event parameter must be passed from the HTML attribute: onsubmit="handleSubmit(event)"
  • After preventing the default, you can handle the data yourself with JavaScript
Example 4 — oninput for Real-Time Feedback
<input id="search" type="text" oninput="liveSearch(this)"
       placeholder="Type to search...">
<p id="result"></p>

<script>
  let items = ["Apple", "Banana", "Mango", "Grapes", "Orange"];

  function liveSearch(input) {
    let query = input.value.toLowerCase();
    let match = items.filter(i => i.toLowerCase().includes(query));
    document.getElementById("result").textContent =
      query ? "Found: " + match.join(", ") : "";
  }
</script>
Live Preview
Explanation
  • oninput fires on every character change — faster and more responsive than onkeyup
  • this refers to the element that fired the event — a shortcut to avoid getElementById
  • This pattern powers every live search and filter interface on the web
4

Real-Life Example

Think of a doorbell system — the event model maps perfectly:

onclick
Someone presses the doorbell — the press is the event
Handler
The bell rings — the function that responds to the event
onkeydown
Typing a PIN digit on a keypad — detected the moment the key goes down
onsubmit
Pressing "Confirm" on an order — triggers the form submission logic
preventDefault
Intercepting the doorbell signal before it reaches the speaker
event.key
Identifying which button was pressed — "which key on the keypad?"
5

HTML + JavaScript Example

Click ▶ Preview to see all three event types — mouse, keyboard, and form — working together in a single page.

Live in Browser — All Three Event Types
<!DOCTYPE html>
<html>
<head><title>Events Demo</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Event Handling Demo</h2>

  <!-- Mouse event -->
  <button onclick="handleClick()"
    style="padding:8px 18px;background:#f7df1e;border:none;border-radius:6px;
           cursor:pointer;font-weight:700;font-size:1rem">
    Click Me
  </button>

  <!-- Keyboard event -->
  <input type="text" onkeyup="handleKey(event)"
    placeholder="Type something..."
    style="display:block;margin:12px 0;padding:8px 12px;
           border:1px solid #ccc;border-radius:6px;font-size:1rem;width:240px">

  <!-- Form event -->
  <form onsubmit="handleSubmit(event)"
    style="display:flex;gap:8px;align-items:center">
    <input id="nameIn" type="text" placeholder="Enter name"
      style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;
             font-size:1rem;width:180px">
    <button type="submit"
      style="padding:8px 18px;background:#4ade80;border:none;border-radius:6px;
             cursor:pointer;font-weight:700;font-size:1rem">
      Submit
    </button>
  </form>

  <div id="log"
    style="margin-top:16px;font-family:monospace;font-size:0.9rem;
           background:#1e1e2e;color:#cdd6f4;border-radius:8px;padding:14px;
           min-height:60px;line-height:2">
    Waiting for events...
  </div>

  <script>
    let logEl = document.getElementById("log");

    function addLog(msg) {
      logEl.innerHTML = msg + "<br>" + logEl.innerHTML;
    }

    function handleClick() {
      addLog("🖱 Mouse: button clicked");
    }

    function handleKey(event) {
      addLog("⌨ Key up: [" + event.key + "]  value: "" + event.target.value + """);
    }

    function handleSubmit(event) {
      event.preventDefault();
      let name = document.getElementById("nameIn").value.trim();
      addLog("📋 Form submitted: " + (name || "(empty)"));
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Welcome alert button
Starter code
<button onclick="greet()">Click Me</button>

<script>
  function greet() {
    // show alert "Welcome Aman"
  }
</script>
  • Complete the greet() function to show "Welcome Aman"
  • Update it to show the current time using new Date().toLocaleTimeString()
  • Change the button text to "Clicked!" after the first click using event.target.textContent
Medium Task 2 — Live typing logger & form guard
Starter code
<input type="text" oninput="logTyping(event)"
       placeholder="Type here...">

<form onsubmit="submitForm(event)">
  <input id="email" type="text" placeholder="Email">
  <button type="submit">Submit</button>
</form>
  • In logTyping(), print "Typing: [value]" using event.target.value
  • In submitForm(), call event.preventDefault() first — then log the email
  • Add a check: if the email is empty, show "Email required" instead
7

MCQs

Q1
Which event fires when a button is clicked?
<button onclick="console.log('clicked')">Go</button>
Live Preview
  • A onhover
  • B onclick
  • C onpress
  • D onchange
💡 B is correct. onclick handles mouse click events on any element. onhover and onpress do not exist in standard HTML. onchange fires when an input's value changes and focus is lost.
Q2
Which event fires when a key is pressed down on an input?
  • A onsubmit
  • B onclick
  • C onkeydown
  • D onchange
💡 C is correct. onkeydown fires the moment a key is pressed. onkeyup fires when it is released. oninput fires when the value actually changes — the most common choice for real-time text detection.
Q3
What does event.preventDefault() do on a form submission?
<form onsubmit="handle(event)">
  <button type="submit">Submit</button>
</form>
<script>
  function handle(e) {
    e.preventDefault();
    console.log("Handled in JS — no reload!");
  }
</script>
Live Preview
  • A Stops JavaScript from running
  • B Prevents the browser's default action (page reload)
  • C Forces a page reload
  • D Adds a new event listener
💡 B is correct. event.preventDefault() cancels the browser's built-in default behaviour for that event. For forms, the default is to reload the page and send data to a server — calling this lets you handle the data entirely in JavaScript.
8

Pro Tips & Extra Knowledge

  • 01

    Know the difference between keydown, keyup, and input — each fires at a different moment:

    keydown vs keyup vs input
    <input id="demo" type="text" placeholder="Watch the console"
      onkeydown="console.log('DOWN:', event.key)"
      onkeyup="console.log('UP:  ', event.key)"
      oninput="console.log('INPUT value:', this.value)">
    Live Preview
  • 02

    Prefer addEventListener() over inline onclick="" attributes — it keeps HTML and JavaScript separate and allows multiple handlers on the same element:

    addEventListener — the modern approach
    <button id="myBtn">Click me</button>
    <script>
      // Inline (avoid) → ties logic to HTML
      // <button onclick="...">
    
      // addEventListener (preferred) → separates concerns
      document.getElementById("myBtn").addEventListener("click", function() {
        console.log("Clicked via addEventListener!");
      });
    </script>
    Live Preview
  • 03

    The event object gives you rich information about any event — always pass it to your handler when you need context:

    Useful event object properties
    // event.type     — "click", "keyup", "submit"…
    // event.target   — the element that fired the event
    // event.key      — which key was pressed (keyboard events)
    // event.clientX  — mouse X position on screen (mouse events)
    
    document.addEventListener("click", function(e) {
      console.log("Type:", e.type);
      console.log("Target:", e.target.tagName);
      console.log("Position:", e.clientX, e.clientY);
    });
    Output
    Click ▶ Run — then click anywhere on the page
  • 04

    Never forget event.preventDefault() on form submit handlers — without it the page reloads and your JavaScript never gets to process the data.

Mini Challenge

Will the page reload after the alert shows? Why or why not? Think before clicking Submit in the preview.

What happens when you submit this form?
<form onsubmit="handleIt(event)">
  <button type="submit">Submit</button>
</form>

<script>
  function handleIt(event) {
    event.preventDefault();
    alert("Form submitted!");
  }
</script>
Live Preview
Step-by-Step Explanation
// Step 1: User clicks the Submit button
//         The browser fires the "submit" event on the form
//         onsubmit calls handleIt(event)

// Step 2: event.preventDefault() is called FIRST
//         This cancels the browser's default action:
//         the page will NOT reload

// Step 3: alert("Form submitted!") runs
//         The alert appears — and since the page did NOT reload,
//         when the user clicks OK everything stays as it was

// Answer: NO — the page will NOT reload.
//         event.preventDefault() stopped it.

// What if you removed event.preventDefault()?
//   The page WOULD reload immediately after the alert
//   because the browser resumes its default submit behaviour.

// Key rule:
//   Default form behaviour → reload / navigate to action URL
//   With event.preventDefault() → you handle everything in JS