JavaScript Events

Reviewed & published by Brayan K

Learn how to make your web pages come alive by responding to user interactions like clicks, key presses, and form submissions.

Part of the free JavaScript course at LearnCodingFast โ€” hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

What You'll Learn in This Lesson

๐Ÿ’ก Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:

๐ŸŽฏ Real-World Analogy: Events are like a hotel receptionist:

๐Ÿง  What Are Events?

An event is an action that occurs in the browser.

Event TypeWhen It FiresCommon Use
clickUser clicks elementButtons, links, cards
keydownUser presses a keyKeyboard shortcuts, games
submitForm is submittedLogin, search forms
mouseoverMouse hovers elementTooltips, previews

JavaScript allows you to listen for these events and respond to them โ€” this is called event handling.

๐Ÿ’ก Without events, your web pages would be static and non-interactive.

โš™๏ธ Example: Simple Click Event

<button id="clickMe">Click Me!</button>
const button = document.getElementById("clickMe");

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

This is the basic pattern of all JavaScript interactivity โ€” select โ†’ listen โ†’ respond.

๐Ÿงฉ Adding Event Listeners

The modern and most reliable way to handle events is with addEventListener().

๐Ÿ“˜ Syntax:

element.addEventListener(eventType, function);

๐Ÿง  Example: Button Click

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

Or using arrow functions (modern ES6 style):

button.addEventListener("click", () => {
    console.log("You clicked the button!");
});

๐Ÿ–ฑ๏ธ Mouse Events

Mouse events are triggered when the user interacts with the mouse.

Here are the most common ones:

EventDescription
clickWhen the element is clicked
dblclickDouble-click event
mouseenterWhen the cursor enters the element
mouseleaveWhen the cursor leaves the element
mousemoveFires repeatedly as the mouse moves

๐Ÿงฉ Example:

<button id="mouseBtn">Hover or Click</button>
const btn = document.getElementById("mouseBtn");

btn.addEventListener("click", () => console.log("Clicked!"));
btn.addEventListener("dblclick", () => console.log("Double-clicked!"));
btn.addEventListener("mouseenter", () => console.log("Mouse entered!"));
btn.addEventListener("mouseleave", () => console.log("Mouse left!"));
Mouse entered!
Clicked!
Mouse left!

โŒจ๏ธ Keyboard Events

Keyboard events happen when users press keys on their keyboard.

They're often used in forms, games, or shortcuts.

EventDescription
keydownFires when a key is pressed down
keyupFires when a key is released
keypressDeprecated โ€” use keydown instead

Example:

document.addEventListener("keydown", (event) => {
    console.log("Key pressed:", event.key);
});

document.addEventListener("keyup", (event) => {
    console.log("Key released:", event.key);
});
Key pressed: a
Key released: a

๐Ÿงพ Form Events

Forms have their own events โ€” they're essential for validating input and handling data without refreshing the page.

EventDescription
submitTriggered when form is submitted
inputFires while the user is typing
changeFires when an input value changes (after losing focus)
focusWhen an input gets focus
blurWhen an input loses focus

๐Ÿ’ก Example: Prevent Default Submission

<form id="userForm">
  <input type="text" placeholder="Enter name" id="nameInput" />
  <button type="submit">Submit</button>
</form>
const form = document.getElementById("userForm");

form.addEventListener("submit", (event) => {
    event.preventDefault(); // Prevents form refresh
    console.log("Form submitted!");
});
Form submitted!

๐Ÿ’ก Always use event.preventDefault() when handling form data in JavaScript โ€” it stops the browser from reloading the page.

Example: Input Events

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

input.addEventListener("input", () => {
    console.log("Value changed:", input.value);
});
Value changed: Brayan

Every keystroke triggers the event in real time.

๐Ÿง  The Event Object

Whenever an event happens, JavaScript automatically passes an event object to the callback function.

It contains details about the event, like:

document.addEventListener("click", (event) => {
    console.log("Clicked element:", event.target);
    console.log("Event type:", event.type);
});
Clicked element: <button id="mouseBtn">Hover or Click</button>
Event type: click

Example: Stopping Default Behavior

Some elements (like links or forms) have default behaviors.

You can stop those actions using event.preventDefault().

<a href="https://google.com" id="link">Go to Google</a>
const link = document.getElementById("link");

link.addEventListener("click", (event) => {
    event.preventDefault();
    console.log("Default action stopped!");
});

๐ŸŸข Result: The link won't open, but the message will appear in the console.

๐ŸŽฎ Interactive Example โ€” Key Tracker

Let's create a simple program that displays which key the user pressed.

<h2>Press any key!</h2>
<p id="displayKey">Waiting for input...</p>

๐ŸŸข Output (on the page):

You pressed: a

๐Ÿงฉ Example โ€” Change Background on Click

<button id="colorBtn">Change Background</button>
const colorBtn = document.getElementById("colorBtn");

colorBtn.addEventListener("click", () => {
    document.body.style.backgroundColor =
        document.body.style.backgroundColor === "lightblue"
            ? "white"
            : "lightblue";
});

๐ŸŸข Result: The background toggles each time you click the button!

โš™๏ธ Window Events

The window object represents the browser window itself.

You can detect changes like loading, resizing, or scrolling.

Example: Page Load

window.addEventListener("load", () => {
    console.log("Page fully loaded!");
});

Example: Window Resize

window.addEventListener("resize", () => {
    console.log("Window resized to:", window.innerWidth, "x", window.innerHeight);
});

Example: Scroll Event

window.addEventListener("scroll", () => {
    console.log("You scrolled!");
});

๐Ÿ“š Common Event Types Reference

๐Ÿ–ฑ๏ธ Mouse Events

โŒจ๏ธ Keyboard Events

๐Ÿงพ Form Events

๐ŸŒ Window Events

๐ŸŽฏ Practice Challenge

Create event handlers for the following:

1๏ธโƒฃ A click event that logs a message

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

2๏ธโƒฃ A keyboard event that detects specific keys

document.addEventListener("keydown", (e) => {
    if (e.key === "Enter") {
        console.log("You pressed Enter!");
    }
});

3๏ธโƒฃ A form submission that prevents default behavior

form.addEventListener("submit", (e) => {
    e.preventDefault();
    console.log("Form submission prevented!");
});

4๏ธโƒฃ Use the event object to log event properties

element.addEventListener("click", (event) => {
    console.log("Target:", event.target);
    console.log("Type:", event.type);
});

๐Ÿ’ฌ Recap

Every interactive feature โ€” from pressing Play on YouTube to typing in a search bar โ€” starts with a JavaScript event.

Mastering events turns you from a coder into a true frontend developer!

End of Lesson: JavaScript Events

๐Ÿ“‹ Quick Reference โ€” JavaScript Events

EventWhen It Fires
clickUser clicks element
keydownKey is pressed
submitForm is submitted
inputUser types into field
addEventListenerel.addEventListener('click', fn)

Lesson Complete โ€” JavaScript Events!

You can now make web pages respond to user interactions โ€” clicks, typing, scrolling, and form submissions!

Practice quiz

What is the modern, recommended way to handle an event?

  • element.onclick = fn
  • element.attachEvent(fn)
  • element.addEventListener(type, fn)
  • element.handle(fn)

Answer: element.addEventListener(type, fn). addEventListener is the modern, reliable way and lets you attach multiple listeners without overwriting.

When does the 'click' event fire?

  • When the user clicks the element
  • When a key is pressed
  • When a form is submitted
  • When the page loads

Answer: When the user clicks the element. The click event fires when the user clicks the element โ€” used for buttons, links, and cards.

What does event.preventDefault() do?

  • Stops the event from firing
  • Removes the listener
  • Logs the event
  • Stops the browser's default action, like a form reload

Answer: Stops the browser's default action, like a form reload. preventDefault stops default behaviour such as a form submitting/reloading or a link navigating.

Which property tells you which key was pressed in a keydown handler?

  • event.code only
  • event.key
  • event.value
  • event.pressed

Answer: event.key. event.key gives the value of the key the user pressed.

How many listeners can you attach to one element with addEventListener?

  • As many as you want โ€” they do not overwrite each other
  • Only one
  • Up to three
  • One per event type, replacing the previous

Answer: As many as you want โ€” they do not overwrite each other. addEventListener lets you attach as many listeners as you like; they all run and none overwrite the others.

Which form event fires while the user is typing in a field?

  • submit
  • blur
  • input
  • load

Answer: input. The input event fires on every keystroke in real time as the value changes.

Which property of the event object is the element that triggered it?

  • event.element
  • event.target
  • event.source
  • event.node

Answer: event.target. event.target references the element that triggered the event; event.type gives the event's name.

Which event fires when an input loses focus?

  • focus
  • input
  • change
  • blur

Answer: blur. blur fires when an element loses focus; focus fires when it gains focus.

Which keyboard event is deprecated, with keydown recommended instead?

  • keyup
  • keypress
  • keydown
  • keyhold

Answer: keypress. keypress is deprecated; the lesson recommends using keydown instead.

On the window object, which event signals the page has fully loaded?

  • ready
  • open
  • load
  • start

Answer: load. window's 'load' event fires when the page is fully loaded.

Continue this course