Guest Mode:

BCA Student Stories & UpdatesLive

You
Your StorySign in & share
Er. Manoj Kumar
D5
Er. ManojActive nowPages
Day 29DOM & Web APIs2 Hours Practical
Push to GitHub to Complete

DOM Events: addEventListener, Click, Input & Form Submission with preventDefault

Web applications are event-driven. An event is a signal that something has happened—a button click, a key press, or a form submission. Event listeners listen silently for these user actions and trigger handler functions in response.

Interactive Learning Roadmap

Day 29 Step-by-Step Practical Flow

🎯1. What You Will Learn Today

✔Bind event handlers cleanly using element.addEventListener().
✔Handle user clicks, real-time typing input events, and form submit events.
✔Prevent destructive browser default actions using event.preventDefault().
✔Build interactive widgets like real-time character counters and live text mirrormen.
Day 29 MasterclassDOM & Web APIs

DOM Events: addEventListener, Click, Input & Form Submission with preventDefault — Comprehensive Practical Guide

Har concept ko visual mental models, code anatomy aur practical industry tips ke sath samjhein.

Real-World Purpose Aur Zaroorat

Web applications are event-driven. An event is a signal that something has happened—a button click, a key press, or a form submission. Event listeners listen silently for these user actions and trigger handler functions in response.

element.addEventListener("event", callback): Registers an event handler without overwriting other handlers.
"click" event: Fires when a user clicks with mouse or taps on a touch screen.
"input" event: Fires synchronously every time an input or textarea value changes.
"submit" event: Fires on <form> when the user submits (presses Enter or clicks submit button).
event.preventDefault(): Stops default browser behaviors (such as form submission refreshing the webpage).
Event Object (e): Provides event metadata like e.target.value or e.key.
Dimaag Mein Bithane Ka Model

"Think of an event listener like a doorbell chime receiver: it sits quietly waiting for someone to press the physical button (event), and the moment the button is pressed, it rings the indoor chime (handler function)."

💡 Pro Tip: Code ko ratta mat maaro; imagine karo ki browser har tag ko visually kaise draw karta hai.

👨‍🏫3. Teacher Demonstration Code

See how addEventListener handles button clicks and tracks character input in real time.

Interactive Click Counter and Live Character Counterhtml
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    .btn { padding: 8px 16px; background: #2563eb; color: #fff; border: none; border-radius: 4px; cursor: pointer; }
  </style>
</head>
<body>
  <h3>Interactive Counter</h3>
  <button id="counter-btn" class="btn">Clicks: <span id="count">0</span></button>

  <h3 style="margin-top: 24px;">Live Feedback Input</h3>
  <input type="text" id="feedback-input" placeholder="Type a message..." style="padding: 8px; width: 260px;" />
  <p>Character count: <span id="char-count">0</span></p>

  <script>
    let clicks = 0;
    const btn = document.querySelector("#counter-btn");
    const countDisplay = document.querySelector("#count");

    btn.addEventListener("click", () => {
      clicks++;
      countDisplay.textContent = clicks;
    });

    const input = document.querySelector("#feedback-input");
    const charDisplay = document.querySelector("#char-count");

    input.addEventListener("input", (e) => {
      charDisplay.textContent = e.target.value.length;
    });
  </script>
</body>
</html>

2. Hands-On Practical Lab: Follow Instructions in VS Code

Code like a professional software engineer! Follow the step-by-step instructions below in Visual Studio Code (VS Code) on your PC, test your output locally, and push to GitHub.

2 Coding Tasks
Interactive Coding TestAuto-Evaluates as you type

Day 29 Practical Task Test Studio

Test Score:0 / 2 Passed
1. Practical Task Specifications & Live Test Checklist:Type code below to pass tests
Task 1Attach submit listener with preventDefault

Add a submit event listener to form that accepts event e and executes e.preventDefault().

⏳ WAITING
Task 2Show confirmation message

Inside the submit handler, set confirmation.textContent = "Registration Successful!" and confirmation.style.display = "block".

⏳ WAITING
2. Type HTML & CSS Code:index.html
index.html
⚡ Real-Time Testing Active
Tab inserts 2 spaces • Live DOM refresh592 chars
Live Browser Output:
🔒 http://localhost:5500/index.html
Live
Renders live HTML & CSS typed on the left.
Interactive Bug Detective

Spot the Bug: Calling Function Immediately Instead of Passing Reference

Tap or click on the exact line below that contains the error:

Click any code line
⚠️ Broken Code Inspector
Tap buggy line
1
function handleButtonClick() {
2
console.log("Button clicked!");
3
}
4
5
const btn = document.querySelector("#my-btn");
6
// Bug: Calling the function with () inside addEventListener!
7
btn.addEventListener("click", handleButtonClick());
Stuck? Need a detective clue before checking the solution?

Senior Developer Forensic Analysis:

Passing handleButtonClick() with parentheses invokes the function immediately when the line is parsed, passing its return value (undefined) to addEventListener instead of passing the function reference.

Golden Rule: Always validate code syntax and security attributes before pushing to GitHub!

📝Independent Practice: Assignment

📄 note-taker.html

Interactive Live Note Taker with Character Count

  • •Create day-29/index.html with a form containing a textarea and submit button.
  • •Add an "input" event listener displaying real-time character count (e.g. 42 / 200).
  • •Change character counter color to red if character count exceeds 180.
  • •Add a submit listener that appends the note as a new paragraph element in the DOM.
Submission Evaluation Criteria: Ensure the form submission does not reload the page and uses e.preventDefault().
Exact Assignment Solution Code: note-taker.html

Open Visual Studio Code on your PC (code .), create note-taker.html, paste this complete step-by-step verified code, test in your browser, and push to your GitHub repo:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>BCA Day 29 - Interactive Live Note Taker</title>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Segoe UI', Tahoma, sans-serif;
      background: #0b1120;
      color: white;
      min-height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px;
    }
    .note-app {
      background: #1e293b;
      border: 1px solid #334155;
      border-radius: 16px;
      padding: 28px;
      max-width: 480px;
      width: 100%;
    }
    h1 { font-size: 20px; color: #38bdf8; margin-bottom: 16px; }
    textarea {
      width: 100%;
      height: 100px;
      background: #0f172a;
      border: 1px solid #334155;
      border-radius: 8px;
      padding: 12px;
      color: white;
      font-family: inherit;
      font-size: 13px;
      resize: vertical;
      outline: none;
    }
    textarea:focus { border-color: #2563eb; }
    .counter-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 8px 0 16px;
      font-size: 12px;
      color: #94a3b8;
    }
    .warning { color: #ef4444; font-weight: bold; }
    .btn-submit {
      width: 100%;
      padding: 10px;
      background: #2563eb;
      border: none;
      border-radius: 8px;
      color: white;
      font-weight: bold;
      cursor: pointer;
    }
    .notes-list { margin-top: 24px; list-style: none; }
    .note-item {
      background: #0f172a;
      border-left: 3px solid #10b981;
      padding: 10px 14px;
      border-radius: 6px;
      margin-bottom: 8px;
      font-size: 13px;
    }
  </style>
</head>
<body>
  <div class="note-app">
    <h1>BCA Quick Lab Note Taker</h1>
    <form id="noteForm">
      <textarea id="noteInput" maxlength="200" placeholder="Type quick lab notes (max 200 chars)..."></textarea>
      <div class="counter-row">
        <span>Character Count:</span>
        <span id="charCount">0 / 200</span>
      </div>
      <button type="submit" class="btn-submit">Add Note</button>
    </form>

    <ul class="notes-list" id="notesList"></ul>
  </div>

  <script>
    const form = document.getElementById("noteForm");
    const textarea = document.getElementById("noteInput");
    const charCount = document.getElementById("charCount");
    const notesList = document.getElementById("notesList");

    // 1. Input Event: Real-time character counter
    textarea.addEventListener("input", () => {
      const currentLength = textarea.value.length;
      charCount.textContent = `${currentLength} / 200`;
      
      // Color red if exceeds 180 characters
      if (currentLength >= 180) {
        charCount.classList.add("warning");
      } else {
        charCount.classList.remove("warning");
      }
    });

    // 2. Form Submit Event with e.preventDefault()
    form.addEventListener("submit", (e) => {
      e.preventDefault();
      const text = textarea.value.trim();
      if (!text) return;

      // Append new note item to DOM
      const li = document.createElement("li");
      li.className = "note-item";
      li.textContent = text;
      notesList.prepend(li);

      // Reset
      textarea.value = "";
      charCount.textContent = "0 / 200";
      charCount.classList.remove("warning");
    });
  </script>
</body>
</html>
Verified Assignment Code Solution (100% Tested & Ready to Run)

🎓4. Viva Check: Mandatory Conceptual Test

What is the purpose of calling event.preventDefault() inside a form submit event handler?

5. Mandatory Step: Push to GitHub to Unlock Next Lesson

Target Repo: html-css-projects

Windows 11 Terminal / VS Code
1$
mkdir day-29
Create a new project folder (day-29)
2$
cd day-29
Change working directory to day-29
3$
git checkout -b feature/day-29-events
4$
git add index.html
5$
git commit -m "feat(day-29): implement dom event listeners and form preventDefault"
Commit staged changes with a descriptive message
6$
git push origin feature/day-29-events
Push local commits directly to your remote GitHub repository
⌨️ Paste into terminal:Ctrl + V✨ Word wrap active (no horizontal cutoff)
Completion Prerequisites VerificationIncomplete Steps
Google Login
✔ Required
VS Code Implementation
Step 4 Viva Check
Own GitHub Project
Required

Exact GitHub Setup Guide & Expected Structure

Day 29 Requirements

Follow these exact folder and file names to prevent verification errors.

1. GitHub Repository
html-css-projects
Must be set to Public
2. Exact FolderNEW
day-29/ or bca-day-29/
Create inside repo root
3. Exact File NameREQUIRED
index.html
⚠️ No spaces or custom names
4. What to Submit Below
https://github.com/YOU/html-css-projects
Or direct link to index.html
Terminal Commands to Create & Push Day 29
1$
# 1. Enter your repository directory
2$
cd html-css-projects
Change working directory to html-css-projects
3$
# 2. Create the exact folder for Day 29
4$
mkdir day-29
Create a new project folder (day-29)
5$
cd day-29
Change working directory to day-29
6$
# 3. Create your code file: index.html
7$
# (Write your Day 29 homework code inside index.html)
8$
# 4. Save, stage, commit and push to GitHub:
9$
git add .
Stage all modified files and new assets for commit
10$
git commit -m "Day 29: DOM Events: addEventListener, Click, Input & Form Submission with preventDefault"
Commit staged changes with a descriptive message
11$
git push origin main
Push local commits directly to your remote GitHub repository
⌨️ Paste into terminal:Ctrl + V✨ Word wrap active (no horizontal cutoff)
How to Avoid "Could not find your practical code file" Errors:
1.Use Lowercase index.html: Avoid spaces or custom names like Alan Turing..html or Index.HTML. Linux/GitHub servers are strictly case-sensitive.
2.Separate Day Folders: Create a new folder day-29/ for today so you don't overwrite previous days.
3.Ensure Public Visibility: If your GitHub repo is Private, automated validation cannot inspect your code. Set it to Public.
4.Check on GitHub Website: Before clicking "Verify", open your repo in Google Chrome to confirm your files were pushed to branch main.
📁 github.com/YOUR_USERNAME/html-css-projects
Branch: main
README.md# BCA Practical Portfolio overview
day-01/Day 1 Prior Lesson
└──index.html
day-02/Day 2 Prior Lesson
└──index.html
day-03/Day 3 Prior Lesson
└──index.html
day-04/Day 4 Prior Lesson
└──index.html
day-05/Day 5 Prior Lesson
└──index.html
day-06/Day 6 Prior Lesson
└──index.html
day-07/Day 7 Prior Lesson
└──index.html
day-08/Day 8 Prior Lesson
└──index.html
day-09/Day 9 Prior Lesson
└──index.html
day-10/Day 10 Prior Lesson
└──index.html
└──styles.css
day-11/Day 11 Prior Lesson
└──index.html
day-12/Day 12 Prior Lesson
└──index.html
day-13/Day 13 Prior Lesson
└──index.html
day-14/Day 14 Prior Lesson
└──index.html
day-15/Day 15 Prior Lesson
└──index.html
day-16/Day 16 Prior Lesson
└──index.html
day-17/Day 17 Prior Lesson
└──index.html
day-18/Day 18 Prior Lesson
└──index.html
day-19/Day 19 Prior Lesson
└──index.html
day-20/Day 20 Prior Lesson
└──index.html
└──styles.css
day-21/Day 21 Prior Lesson
└──index.html
day-22/Day 22 Prior Lesson
└──index.html
day-23/Day 23 Prior Lesson
└──index.html
day-24/Day 24 Prior Lesson
└──index.html
day-25/Day 25 Prior Lesson
└──index.html
day-26/Day 26 Prior Lesson
└──index.html
day-27/Day 27 Prior Lesson
└──index.html
day-28/Day 28 Prior Lesson
└──index.html
day-29/✨ CREATE THIS FOLDER FOR TODAY (Day 29)
└──index.htmlMust contain: addEventListener('click'), addEventListener('submit'), e.preventDefault()
Sequential Progression Enforced

You are welcome to read all notes, inspect code snippets, and practice all exercises of Day 29 freely! To officially submit your GitHub repository and unlock subsequent days in your portfolio, please complete Day 28: DOM Selection: querySelector, textContent, innerHTML & Dynamic Styles first.

Complete Day 28 First
Curriculum & Practical Systems Authored by Er. Manoj Kumar
NextSem Academy • BCA Practical Learning Portal