JavaScript Foundations • StreetGeek Academy

🧠 MODULE 7: Events & Interactivity

Learn how to detect and respond to user actions (clicks, keypresses, scrolls, etc.) and make your site dynamic, responsive, and engaging.

1) What Are Events?

Events are actions that happen in the browser — and JavaScript can “listen” for them and respond.

Common examples:

  • Clicking a button
  • Typing in an input
  • Submitting a form
  • Hovering over an element
  • Scrolling or resizing the window

When an event occurs, you can run code in response.

2) The addEventListener() Method

Attach an event listener to any element:

element.addEventListener("event", callbackFunction);

Example

const btn = document.getElementById("clickMe");

btn.addEventListener("click", () => {
  console.log("Button clicked!");
});
✅ The second argument (callback function) runs whenever the event triggers.

3) Common Event Types

Event Trigger Example Use
click When clicked Buttons, links
mouseover / mouseout Hover enter/leave Animations
input While typing Live form feedback
submit Form submission Validation
keydown / keyup Keyboard actions Hotkeys, search
scroll Page scroll Lazy loading, animations
change Value change Dropdowns, checkboxes
💡 addEventListener works with all of these and more.

4) Example: Toggle a Navigation Menu

HTML

<button id="menu-btn">☰ Menu</button>
<nav id="nav" class="hidden">
  <a href="#">Home</a>
  <a href="#">Projects</a>
  <a href="#">Contact</a>
</nav>

CSS

.hidden { display: none; }

JavaScript

const menuBtn = document.getElementById("menu-btn");
const nav = document.getElementById("nav");

menuBtn.addEventListener("click", () => {
  nav.classList.toggle("hidden");
});
✅ You just built a collapsible mobile menu with a few lines of JS!

5) Event Objects

Each event automatically sends an event object with useful info.

Example

document.addEventListener("click", (event) => {
  console.log("Clicked element:", event.target);
});
Property Description
event.target The element that triggered the event.
event.type Type of event (click, scroll, etc.).
event.preventDefault() Stops default behavior (like form submission).

6) Example: Custom Button Interaction

HTML

<button id="like-btn">❤️ Like</button>
<p id="likes">Likes: 0</p>

JavaScript

const likeBtn = document.getElementById("like-btn");
const likesDisplay = document.getElementById("likes");
let likes = 0;

likeBtn.addEventListener("click", () => {
  likes++;
  likesDisplay.textContent = `Likes: ${likes}`;
});
✅ Every click updates the count — this is the foundation of interactivity.

7) Listening for Input Events

HTML

<input type="text" id="nameInput" placeholder="Enter your name" />
<p id="preview"></p>

JavaScript

const nameInput = document.getElementById("nameInput");
const preview = document.getElementById("preview");

nameInput.addEventListener("input", () => {
  preview.textContent = `Hello, ${nameInput.value || "friend"}!`;
});
✅ As the user types, the preview updates in real time.

8) Form Submission & Validation

HTML

<form id="contactForm">
  <input type="email" id="email" placeholder="Your email" required />
  <button type="submit">Send</button>
</form>
<p id="status"></p>

JavaScript

const form = document.getElementById("contactForm");
const status = document.getElementById("status");

form.addEventListener("submit", (e) => {
  e.preventDefault();
  const email = document.getElementById("email").value;

  if (email.includes("@")) {
    status.textContent = "✅ Message sent successfully!";
  } else {
    status.textContent = "⚠️ Please enter a valid email.";
  }
});
✅ Prevents page reload and gives instant feedback to users.

9) Keyboard & Scroll Events

Keyboard Example

document.addEventListener("keydown", (e) => {
  console.log(`You pressed: ${e.key}`);
});

Scroll Example

window.addEventListener("scroll", () => {
  console.log("Scrolling at", window.scrollY);
});
💡 Combine with CSS animations or header shrink effects for modern UI touches.

10) Event Delegation (Advanced but Essential)

Instead of adding listeners to every child element, attach one to the parent.

HTML

<ul id="project-list">
  <li>Portfolio</li>
  <li>ShopBlocks</li>
  <li>Nfinite Dashboard</li>
</ul>

JavaScript

const list = document.getElementById("project-list");

list.addEventListener("click", (e) => {
  if (e.target.tagName === "LI") {
    console.log(`Clicked project: ${e.target.textContent}`);
  }
});
✅ Efficient: one event listener for an entire list of elements.

11) Quiz Time

Show/Hide Questions

1) What method attaches an event to an element?

2) What property tells you which element was clicked?

3) How do you prevent a form from reloading the page on submit?

4) What’s the difference between click and input events?

5) Why use event delegation?

🚀 Challenge Task: Add Interactive Components to Your Portfolio

Choose one (or all):

Option A: Dark Mode Toggle

<button id="theme-toggle">🌙 Dark Mode</button>
const toggle = document.getElementById("theme-toggle");

toggle.addEventListener("click", () => {
  document.body.classList.toggle("dark");
  toggle.textContent = document.body.classList.contains("dark")
    ? "☀️ Light Mode"
    : "🌙 Dark Mode";
});

Option B: Accordion Section

<div class="accordion">
  <button class="accordion-header">My Skills</button>
  <div class="accordion-content">HTML, CSS, JS, PHP</div>
</div>
const header = document.querySelector(".accordion-header");

header.addEventListener("click", () => {
  header.nextElementSibling.classList.toggle("active");
});

Option C: Live Character Counter

<textarea id="message" maxlength="150"></textarea>
<p id="counter">150 characters remaining</p>
const textarea = document.getElementById("message");
const counter = document.getElementById("counter");

textarea.addEventListener("input", () => {
  const remaining = 150 - textarea.value.length;
  counter.textContent = `${remaining} characters remaining`;
});
✅ You’re now building user interactions just like professional web apps.

🏁 Module 7 Summary

  • How to attach and handle events
  • How to interact with user input and forms
  • How to use event objects and prevent default actions
  • How to dynamically update your UI in response to events
  • How to apply event delegation for efficient coding

Next up → MODULE 8: Forms & Validation
We’ll take your interactivity further by validating user input, displaying error messages, and improving UX — all within your live portfolio site.