JavaScript in the browser

Beginner 12 min read

Make pages interactive: react to events, change the page and load data from an API.

Why it matters

Interactive features — forms that validate, lists that filter, data that loads without a reload — are JavaScript talking to the page (the DOM) and to the server. Frameworks automate this, but bugs are easier to find when you know what they do underneath.

Where it fits

  1. Plan & Design
  2. ● Develop › Frontend
  3. Version control
  4. Verify
  5. Build & Package
  6. CI/CD
  7. Deploy
  8. Operate

What you will learn

  • Find elements and react to clicks and form input.
  • Load JSON from an API with fetch and show it safely.
  • Handle the loading and error states of a request.

Before you start

Events and the DOM

app.js
const list = document.querySelector('#orders');
const button = document.querySelector('#reload');

async function load() {
  button.disabled = true;
  try {
    const response = await fetch('/api/orders');
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const orders = await response.json();
    list.replaceChildren(...orders.map((o) => {
      const li = document.createElement('li');
      li.textContent = o.name; // text, never HTML
      return li;
    }));
  } catch (error) {
    list.textContent = 'Could not load orders.';
  } finally {
    button.disabled = false;
  }
}

button.addEventListener('click', load);

Watch out: Putting data from a server or a user into innerHTML lets anyone inject scripts into your page (cross-site scripting). Use textContent, or a framework that escapes for you.

Three states of every request

  • Loading — show that something is happening, and prevent a second click.
  • Success — show the data.
  • Error — say what went wrong and how to retry. fetch only rejects on network failure; check response.ok for 4xx and 5xx.

Tip: TypeScript adds types on top of JavaScript and catches many of these mistakes before the code runs. It is worth adopting once a frontend grows past a few files.

Official documentation and references

Documentation

Reference

Practise in Zerethon IDE

Learn next

Done with this topic?

Reviewed 2026-10-23. Links go to the official documentation unless marked otherwise.