← Back to course

Events

Events

Welcome back.

In the previous lesson, you learned the DOM.

The DOM lets JavaScript read and change the web page.

Very useful.

Very visible.

Very “look, the page moved!” energy.

But now we need something even more important.

Interaction.

A page should not only sit there like a very expensive poster.

It should react.

When a user clicks a button, something should happen.

When a user types text, something should happen.

When a user submits a form, something should happen.

This is where events come in.

Events are how JavaScript reacts to users.

The browser says:

Something happened.

JavaScript says:

I have a function for that.

And frontend development begins.

With confidence.

And occasional screaming.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, your pages will react to user actions.

Buttons will respond.

Inputs will update text.

Forms will stop behaving like wild animals.

Mostly.

What Is an Event?

An event is something that happens in the browser.

Examples:

Events happen constantly.

The browser is basically a very busy receptionist saying:

Click happened.
Key pressed.
Input changed.
Form submitted.
Mouse moved.
Another click happened.
Help.

JavaScript can listen for these events.

Then it can run a function.

That function decides what should happen next.

Create the Project

Create a folder for this lesson:

mkdir javascript-lesson8
cd javascript-lesson8
touch index.html
touch script.js

Your project should look like this:

javascript-lesson8/
  index.html
  script.js

Open the folder in your editor.

Today we are building interactive pages.

The browser is no longer just showing content.

It is preparing to listen.

Like a dramatic customer support agent.

Write the HTML

Open index.html and add this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Events</title>
</head>
<body>
  <h1>Events</h1>

  <button id="helloButton">Say Hello</button>

  <p id="message">Click the button.</p>

  <script src="script.js"></script>
</body>
</html>

Now open script.js.

We have:

Very simple.

Very powerful.

Like a small screwdriver that can accidentally fix the internet.

Your First Event Listener

To react to an event, we use addEventListener.

Add this to script.js:

const helloButton = document.getElementById("helloButton");
const messageElement = document.getElementById("message");

function sayHello() {
  messageElement.textContent = "Hello from JavaScript!";
}

helloButton.addEventListener("click", sayHello);

Refresh the browser.

Click the button.

The message changes.

Congratulations.

Your page reacted to a user action.

That is a big moment.

The page is no longer a poster.

It is now a slightly intelligent poster.

How addEventListener Works

Look at this line:

helloButton.addEventListener("click", sayHello);

It means:

When the button is clicked, run the sayHello function.

There are two important parts:

"click"

This is the event type.

sayHello

This is the function that should run.

Important:

We write:

sayHello

not:

sayHello()

Why?

Because we do not want to run the function immediately.

We want to give the function to JavaScript and say:

Run this later, when the click happens.

If you write this:

helloButton.addEventListener("click", sayHello());

the function runs immediately.

That is a classic beginner trap.

It waits behind the door with a banana peel.

Click Events

The click event is one of the most common events.

Example:

const button = document.getElementById("helloButton");

button.addEventListener("click", function () {
  console.log("Button clicked!");
});

This uses an anonymous function.

Anonymous means the function has no name.

It is created directly inside addEventListener.

This is fine for small actions.

But for bigger logic, named functions are usually cleaner:

function handleClick() {
  console.log("Button clicked!");
}

button.addEventListener("click", handleClick);

Both work.

Use the version that keeps your code readable.

Readable code is a gift to your future self.

And your future self is already tired.

The Event Object

When an event happens, JavaScript can give us information about that event.

This information is stored in the event object.

Example:

helloButton.addEventListener("click", function (event) {
  console.log(event);
});

Click the button and check the console.

You will see a lot of information.

A lot.

Maybe too much.

The browser says:

You wanted event details?
Here is a suitcase.

The event object can tell us things like:

Very useful.

Very detailed.

Slightly overwhelming.

event.target

One useful property is event.target.

It tells us which element caused the event.

Example:

helloButton.addEventListener("click", function (event) {
  console.log(event.target);
});

When you click the button, the console shows the button element.

event.target means:

The element that triggered the event.

This is useful when one function handles many elements.

For example, many buttons.

Many cards.

Many tiny sources of chaos.

Input Events

Events are not only for buttons.

They also work with inputs.

Update index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Events</title>
</head>
<body>
  <h1>Events</h1>

  <label for="nameInput">Your name:</label>
  <input id="nameInput" type="text" placeholder="Type your name">

  <p id="preview">Your name will appear here.</p>

  <script src="script.js"></script>
</body>
</html>

Now update script.js:

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

function updatePreview(event) {
  previewElement.textContent = `Hello, ${event.target.value}!`;
}

nameInput.addEventListener("input", updatePreview);

Refresh the browser.

Type your name.

The paragraph updates while you type.

This is the input event.

It runs every time the input value changes.

Very useful for:

Getting Input Value

The value of an input is stored in .value.

Example:

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

console.log(nameInput.value);

Inside an event function, you can use:

event.target.value

Example:

function updatePreview(event) {
  const name = event.target.value;
  previewElement.textContent = `Hello, ${name}!`;
}

This is very common.

User types.

JavaScript reads the value.

Page updates.

Simple.

Clean.

Like washing dishes immediately instead of creating a kitchen disaster.

Rare.

But beautiful.

Keyboard Events

JavaScript can also react to keyboard actions.

Example:

document.addEventListener("keydown", function (event) {
  console.log(`You pressed: ${event.key}`);
});

Refresh the browser.

Press keys.

The console shows which key you pressed.

Examples:

You pressed: a
You pressed: Enter
You pressed: Escape

Keyboard events are useful for:

Do not abuse keyboard shortcuts.

Nobody wants a website where pressing K accidentally buys a refrigerator.

Form Submit Events

Forms have a special event called submit.

Update index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Events</title>
</head>
<body>
  <h1>Events</h1>

  <form id="contactForm">
    <label for="emailInput">Email:</label>
    <input id="emailInput" type="email" placeholder="you@example.com">

    <button type="submit">Send</button>
  </form>

  <p id="formMessage">Submit the form.</p>

  <script src="script.js"></script>
</body>
</html>

Now update script.js:

const contactForm = document.getElementById("contactForm");
const emailInput = document.getElementById("emailInput");
const formMessage = document.getElementById("formMessage");

function handleSubmit(event) {
  event.preventDefault();

  formMessage.textContent = `Thanks! We received: ${emailInput.value}`;
}

contactForm.addEventListener("submit", handleSubmit);

Refresh the browser.

Type an email.

Submit the form.

The page does not reload.

The message changes.

Very nice.

Very frontend.

Very “we are controlling the chaos now.”

Why preventDefault Is Important

By default, when a form is submitted, the browser reloads the page.

That is normal browser behavior.

But in JavaScript projects, we often want to handle the form ourselves.

So we use:

event.preventDefault();

This means:

Stop the browser's default behavior.
I will handle this with JavaScript.

Without it, the page reloads.

Your message disappears.

Your soul leaves the body.

Then you remember preventDefault.

Classic.

Multiple Event Listeners

One element can have multiple event listeners.

Example:

const button = document.getElementById("helloButton");

button.addEventListener("click", function () {
  console.log("First listener");
});

button.addEventListener("click", function () {
  console.log("Second listener");
});

When the button is clicked, both functions run.

This can be useful.

But be careful.

Too many listeners can make code difficult to follow.

Your button should not have the emotional complexity of a detective novel.

Keep things organized.

Build an Interactive Feedback Form

Now let us build a small feedback form.

Update index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Events</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 700px;
      margin: 60px auto;
      padding: 0 24px;
      background-color: #f3f4f6;
      color: #111827;
    }

    .card {
      background-color: white;
      padding: 24px;
      border: 2px solid #e5e7eb;
      border-radius: 18px;
    }

    h1 {
      font-size: 42px;
    }

    label {
      display: block;
      margin-top: 16px;
      font-weight: 700;
    }

    input,
    textarea {
      width: 100%;
      margin-top: 8px;
      padding: 12px;
      border: 2px solid #d1d5db;
      border-radius: 12px;
      font-size: 18px;
      box-sizing: border-box;
    }

    textarea {
      min-height: 120px;
    }

    button {
      margin-top: 18px;
      background-color: #2563eb;
      color: white;
      border: none;
      padding: 14px 20px;
      border-radius: 999px;
      font-weight: 700;
      cursor: pointer;
    }

    button:hover {
      background-color: #1d4ed8;
    }

    .message {
      margin-top: 20px;
      padding: 16px;
      border-radius: 14px;
      background-color: #eff6ff;
      border: 2px solid #bfdbfe;
    }

    .error {
      background-color: #fef2f2;
      border-color: #fecaca;
      color: #991b1b;
    }

    .success {
      background-color: #ecfdf5;
      border-color: #bbf7d0;
      color: #166534;
    }
  </style>
</head>
<body>
  <h1>Events</h1>

  <div class="card">
    <form id="feedbackForm">
      <label for="nameInput">Name</label>
      <input id="nameInput" type="text" placeholder="Your name">

      <label for="feedbackInput">Feedback</label>
      <textarea id="feedbackInput" placeholder="Write your feedback"></textarea>

      <button type="submit">Send Feedback</button>
    </form>

    <p id="message" class="message">Fill the form and submit it.</p>
  </div>

  <script src="script.js"></script>
</body>
</html>

Now update script.js:

const feedbackForm = document.getElementById("feedbackForm");
const nameInput = document.getElementById("nameInput");
const feedbackInput = document.getElementById("feedbackInput");
const messageElement = document.getElementById("message");

function showMessage(text, type) {
  messageElement.textContent = text;
  messageElement.className = `message ${type}`;
}

function handleFeedbackSubmit(event) {
  event.preventDefault();

  const name = nameInput.value;
  const feedback = feedbackInput.value;

  if (name === "" || feedback === "") {
    showMessage("Please fill in all fields.", "error");
    return;
  }

  showMessage(`Thanks, ${name}! Your feedback was received.`, "success");

  nameInput.value = "";
  feedbackInput.value = "";
}

feedbackForm.addEventListener("submit", handleFeedbackSubmit);

Refresh the browser.

Try submitting an empty form.

You should see an error.

Fill the form.

Submit again.

You should see a success message.

The form reacts.

The DOM updates.

The inputs are cleared.

This is very close to real web development.

Not the full backend.

Not the database.

But the frontend behavior is real.

The page is now responding like a civilized creature.

Mostly.

How This Code Works

This finds the form and inputs:

const feedbackForm = document.getElementById("feedbackForm");
const nameInput = document.getElementById("nameInput");
const feedbackInput = document.getElementById("feedbackInput");
const messageElement = document.getElementById("message");

This function shows a message:

function showMessage(text, type) {
  messageElement.textContent = text;
  messageElement.className = `message ${type}`;
}

This function handles the form:

function handleFeedbackSubmit(event) {
  event.preventDefault();

  const name = nameInput.value;
  const feedback = feedbackInput.value;

  if (name === "" || feedback === "") {
    showMessage("Please fill in all fields.", "error");
    return;
  }

  showMessage(`Thanks, ${name}! Your feedback was received.`, "success");

  nameInput.value = "";
  feedbackInput.value = "";
}

This connects the form to the function:

feedbackForm.addEventListener("submit", handleFeedbackSubmit);

Important pattern:

Form submitted.

Default behavior stopped.

Input values checked.

Message displayed.

Inputs cleared.

This pattern appears everywhere.

Contact forms.

Login forms.

Search forms.

Checkout forms.

The internet is basically forms wearing different clothes.

Common Mistakes

Calling the Function Immediately

Wrong:

button.addEventListener("click", handleClick());

Correct:

button.addEventListener("click", handleClick);

Without parentheses, you pass the function.

With parentheses, you call it immediately.

This mistake is very common.

Very sneaky.

Very JavaScript.

Forgetting preventDefault on Forms

Wrong:

function handleSubmit(event) {
  messageElement.textContent = "Form submitted!";
}

Correct:

function handleSubmit(event) {
  event.preventDefault();
  messageElement.textContent = "Form submitted!";
}

Without preventDefault, the page may reload.

Then your changes disappear.

Then you stare at the screen.

Then you remember.

Selecting the Wrong Element

If this returns null:

const button = document.getElementById("sendButton");

Check your HTML.

Maybe the id is different.

Example:

<button id="submitButton">Send</button>

Then JavaScript must use:

const button = document.getElementById("submitButton");

IDs must match exactly.

JavaScript is not a detective.

It will not guess.

Forgetting to Read .value

Wrong:

const name = nameInput;

Correct:

const name = nameInput.value;

The input element is not the same as the value inside it.

The element is the box.

.value is what the user typed into the box.

Very important.

Box.

Content.

Different things.

Like a pizza box and pizza.

Do not eat the box.

Practice

Create a page with:

When the user types something and clicks the button:

Example:

const input = document.getElementById("textInput");
const button = document.getElementById("showButton");
const output = document.getElementById("output");

function showText() {
  output.textContent = input.value;
  input.value = "";
}

button.addEventListener("click", showText);

Then add a condition.

If the input is empty, show:

Please type something.

Run it.

Change it.

Break it.

Fix it.

Events become normal only after practice.

Not after thinking about practice.

I checked.

Mini Challenge

Build a small login form.

The page should have:

Rules:

Example success message:

Login data looks valid.

Do not build a real login system yet.

This is only frontend validation.

No database.

No backend.

No secret hacker bunker.

Just events, inputs, and conditions.

Still useful.

Still important.

Summary

Today you learned:

This is a huge step.

The DOM lets JavaScript change the page.

Events tell JavaScript when to change the page.

Together, they create real interaction.

Buttons respond.

Forms react.

Messages update.

Users click things.

JavaScript tries to keep up.

Heroic.

Slightly stressed.

But heroic.

Next Lesson

In the next lesson, we will learn forms and validation in more detail.

Forms are everywhere on the web.

Contact forms.

Login forms.

Search boxes.

Checkout pages.

Newsletter signups.

Tiny boxes where users type their destiny.

JavaScript will help us check that data before we send it anywhere.