Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Full-Stack Web Development — Alpha School

Lesson 12: Events, Forms and Fetching Data

A page that only changes when it loads is a poster, not an application. What makes a page feel alive is events: the browser notices things happening, a click, a key press, a form being submitted, a page finishing loading, and runs your code in response. You connect code to events with addEventListener, and the pattern is always the same: select an element, name an event, and give it a function to run when that event happens. This lesson covers the events you will use most, how to handle forms without reloading the page, and how to fetch data from a server and display it, which is the skill that turns a static site into a real application.

Listening for events

The call button.addEventListener('click', function () { ... }); says “when this button is clicked, run this function”, and the function receives an event object that describes what happened, such as which key was pressed or where the pointer was. Common events include click, input, which fires every time a field's value changes, submit, which fires when a form is sent, and keydown, which fires when a key is pressed. You can attach several listeners to one element, and you can remove one with removeEventListener, though in practice most listeners stay for the life of the page. A useful pattern is event delegation: instead of adding a listener to every item in a long list, add one listener to the list itself and check event.target to see which item was clicked, which is simpler and works for items added later too.

Handling forms without reloading

When a form is submitted, the browser's default behaviour is to send the data to a server and load a new page, which throws away the current page. For a smooth experience, you usually stop that with event.preventDefault() inside a submit listener, read the values yourself, check them, and decide what to do next, such as showing a message or sending the data in the background. You can read a field's value with input.value, and you can read a whole form at once with new FormData(form), which collects every named field into one object. Validate kindly: check on submit rather than on every keystroke, explain what is wrong in plain words next to the field, and never clear a form a visitor has spent time filling in. The browser's built-in checks, such as required and type="email", still run first, and your JavaScript adds the checks only you can describe, such as whether two passwords match.

const form = document.querySelector('#search-form');
const input = document.querySelector('#query');
const results = document.querySelector('#results');

form.addEventListener('submit', function (event) {
  event.preventDefault();
  const q = input.value.trim();
  if (q === '') {
    results.textContent = 'Type something to search for.';
    return;
  }
  results.textContent = 'Searching for ' + q + '...';
});

Fetching data from a server

The fetch() function asks a server for data without reloading the page, and it returns a promise, which is JavaScript's way of saying “this will finish later”. You handle that with .then() steps or with the cleaner async and await keywords: const response = await fetch('/api/lessons'); const data = await response.json();. The response object tells you whether the request succeeded, with response.ok, and the .json() method reads the body as JSON, the data format you will meet in Unit 4. Always handle failure: wrap the fetch in try and catch, check response.ok before reading the body, and show the visitor a clear message if the request fails, rather than leaving them staring at a spinner. A loading message, a success state and an error state are the three states every data display needs, and building all three is what separates a finished feature from a demo.

Putting it together: a live search

Imagine a search box on a course catalogue. As the visitor types, an input listener reads the value, and when the form is submitted, your code prevents the reload, fetches matching courses from an API, and builds a list of results with createElement, exactly as in the last lesson. If the search returns nothing, you say so plainly, with a suggestion to try a broader word. If the network fails, you say the search is unavailable and offer a link to browse all courses instead. That one feature uses every skill in this unit: selecting elements, listening for events, reading form values, fetching data, handling errors, and updating the DOM. Build it slowly, test each step in the console, and you will have written your first real web application feature, which is a genuine milestone.

Watch & Learn

One video to watch for this unit, from a trusted educator.

  • Learn JavaScript - Full Course for Beginners — freeCodeCamp.org
    Beau Carnes's full JavaScript course covers variables, functions, decisions, loops, objects and the DOM — everything in this unit and more, with worked examples.

Key Terms

Event
Something the browser notices, such as a click, a key press or a form submission.
addEventListener()
A method that runs a function when a named event happens on an element.
event.preventDefault()
A call that stops the browser's default action, such as reloading the page on form submit.
FormData
An object that collects every named field of a form into one set of values.
fetch()
A function that asks a server for data without reloading the page.
Promise
An object representing a value that will arrive later, handled with .then() or async and await.
JSON
JavaScript Object Notation, a text format for data, such as {"title": "French", "lessons": 20}.

Discussion Questions

  1. Why would you add one listener to a whole list instead of a listener to every item in it?
  2. A search box shows a spinning loader forever when the network fails. What three states should it have had, and what should each one say?
  3. Why is it better to validate a form kindly on submit than to interrupt the visitor on every keystroke?

Practice Questions

  1. What does addEventListener('click', fn) do?
  2. Why call event.preventDefault() in a submit listener?
  3. How do you read the value of a text input called input?
  4. What does fetch() return, and how do you get the data out of it?
  5. What should your code do when a fetch fails?
Show answers
  1. It runs fn when the element is clicked. The first argument names the event and the second is the function to run when it happens.
  2. To stop the browser reloading the page. It lets your code handle the submission itself, such as by fetching data and updating the page.
  3. With input.value. That property holds the current text, and .trim() removes extra spaces from the ends.
  4. It returns a promise for a response. You await it, check response.ok, and then read the body, for example with await response.json().
  5. Show the visitor a clear message and an alternative. Catch the error, explain that the data could not be loaded, and offer another way forward, such as browsing the full list.
Keep reading to complete this lesson