JavaScript in the browser
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
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
- HTML and CSS✓ Learned
Events and the DOM
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.
fetchonly rejects on network failure; checkresponse.okfor 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
- MDN — JavaScript ↗ Official · MDN Web Docs
- TypeScript documentation ↗ Official · TypeScript
Reference
- MDN — Document Object Model (DOM) ↗ Official · MDN Web Docs
- MDN — Fetch API ↗ Official · MDN Web Docs
Practise in Zerethon IDE
- Code Help: JavaScript — Variables and types
- Code Help: JavaScript — Promises and async / await async/await, the way fetch is used above.
Learn next
- Frontend frameworks ›✓ Learned
Related topics
- HTTP and APIs✓ Learned
- Frontend frameworks✓ Learned
Done with this topic?
Reviewed 2026-10-23. Links go to the official documentation unless marked otherwise.