Lesson 9: Event Handling

“Build interactivity by listening and responding to user actions.”

Lesson 9: Event Handling

What are Events?

An [event] is an action that occurs on a web page, such as a user clicking a button, hovering over an element, pressing keys on a keyboard, or submitting a form.

JavaScript listens for these actions and triggers code in response using an [event listener].

For a complete list of interactive triggers, view the MDN Event Reference Page.

---

Adding Event Listeners

  • To respond to an event, we attach the addEventListener method to an HTML element. It takes two parameters:
  • The type of event to listen for (e.g., 'click').
  • The callback function to run when the event occurs.

#### Code Example: Interactive Button Click
Assume your HTML document contains:
<button id="action-btn">Click Me</button>
<p id="action-message">Waiting for user interaction...</p>

Write this script in your app.js:
let actionBtn = document.querySelector("#action-btn");
let actionMsg = document.querySelector("#action-message");

actionBtn.addEventListener("click", () => {
actionMsg.textContent = "Button clicked! The interface is officially interactive.";
actionMsg.style.color = "green";
});

#### Visual Output Demonstration:
* When the page loads, it says "Waiting for user interaction...".
* Clicking the button immediately updates the text to green and changes the content to: "Button clicked! The interface is officially interactive.".

---

Processing Form Submissions

Form submissions reload the browser page by default. To create smooth modern interfaces, we prevent this default reload action using event.preventDefault() and read inputs directly.

#### Code Example: Input Capture
Assume your HTML contains:
<form id="signup-form">
<input type="text" id="username-field" placeholder="Enter your name" />
<button type="submit">Submit</button>
</form>
<p id="welcome-log"></p>

Write this script in your app.js:
let signupForm = document.querySelector("#signup-form");
let usernameField = document.querySelector("#username-field");
let welcomeLog = document.querySelector("#welcome-log");

signupForm.addEventListener("submit", (event) => {
// Stop default page refresh behavior
event.preventDefault();

let enteredName = usernameField.value;
welcomeLog.textContent = Welcome to our app, ${enteredName}!;
usernameField.value = ""; // Clear the input field
});

#### Visual Output Demonstration:
* Type "Sarah" into the input field and click Submit.
* The page does not refresh, and a greeting message immediately displays: "Welcome to our app, Sarah!".

---

Frequently Asked Questions (FAQs)

#### Q1: What does the 'event' (or 'e') parameter contain in a callback function?
* The event parameter is an object created by the browser. It contains metadata about the event, such as which key was pressed, where the cursor clicked, or which HTML element triggered the event (event.target).

#### Q2: Can you add multiple event listeners to the same HTML element?
* Yes! You can add multiple event listeners (such as 'click', 'mouseenter', and 'mouseleave') to a single element without conflict.

#### Q3: What is event propagation or bubbling?
* [Event bubbling] is the process where an event runs on a target element, and then triggers upwards on its parent elements. You can stop this behavior using event.stopPropagation() if needed.

Shanawar AliFounder and developer at S Pro Coder, sharing practical coding and technology guides.