Build with DEX · 30 reference entries

Browser JavaScript reference

Use browser APIs for form handling, requests, formatting, storage and progressive enhancement.

These small examples show native browser capabilities. Names such as form, status and loadTopics stand for elements or functions in your own application. The examples are reading material; this library does not execute them or add a third-party editor.

All reference topics · Reviewed source links

Entry index

Choose an entry or use Find on page to look for a term. Each number identifies an educational reference; production checks need their own recorded result.

DOM and events

WEB-JS-002

Writing text safely

Use textContent when inserting plain text supplied by a user or an API. HTML parsing requires a separate trusted-content policy.

Example and documentation
const output = document.querySelector("#result");
if (output) output.textContent = userProvidedText;

Documentation: Browser and JavaScript documentation

Link to WEB-JS-002 · Back to entry index

WEB-JS-003

Creating elements

Create the element, set its text and append it. This keeps data separate from markup construction.

Example and documentation
const item = document.createElement("li");
item.textContent = "Read the form guidance";
document.querySelector("#steps")?.append(item);

Documentation: Browser and JavaScript documentation

Link to WEB-JS-003 · Back to entry index

WEB-JS-004

Waiting for the document

A module or deferred script usually runs after parsing. If loading timing is uncertain, check readyState before registering DOMContentLoaded.

Example and documentation
function start() { /* attach page behaviour */ }
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", start, { once: true });
else start();

Documentation: Browser and JavaScript documentation

Link to WEB-JS-004 · Back to entry index

WEB-JS-005

Event listeners

Attach behaviour with addEventListener. Use once for a one-time action or an AbortSignal to remove a group of listeners.

Example and documentation
const controller = new AbortController();
window.addEventListener("resize", updateLayout, { signal: controller.signal });
// When the component is removed:
controller.abort();

Documentation: Browser and JavaScript documentation

Link to WEB-JS-005 · Back to entry index

WEB-JS-006

Event delegation

Listen on a stable parent for repeated child controls. Validate the target and confirm the matched control belongs to that parent.

Example and documentation
list.addEventListener("click", (event) => {
  if (!(event.target instanceof Element)) return;
  const button = event.target.closest("button[data-id]");
  if (button && list.contains(button)) selectItem(button.dataset.id);
});

Documentation: Browser and JavaScript documentation

Link to WEB-JS-006 · Back to entry index

WEB-JS-007

Form submission

Listen for submit on the form so keyboard submission follows the same path as the button. Prevent the default only when handling the submission yourself.

Example and documentation
form.addEventListener("submit", (event) => {
  event.preventDefault();
  const values = new FormData(form);
  showPreview(values.get("topic"));
});

Documentation: Browser and JavaScript documentation

Link to WEB-JS-007 · Back to entry index

WEB-JS-008

Native form validation

Use browser constraints for immediate guidance, then validate again on the server. Report validity when the user requests an action.

Example and documentation
if (form.reportValidity()) {
  const values = new FormData(form);
  preview.textContent = String(values.get("question") ?? "");
}

Documentation: Browser and JavaScript documentation

Link to WEB-JS-008 · Back to entry index

Requests and asynchronous work

WEB-JS-009

Checking fetch responses

Fetch can fulfil its promise for an HTTP error response. Check response.ok before interpreting the successful response body.

Example and documentation
const response = await fetch("/example-api/topics");
if (!response.ok) throw new Error("Topics could not be loaded");
const topics = await response.json();

Documentation: Browser and JavaScript documentation

Link to WEB-JS-009 · Back to entry index

WEB-JS-010

Sending JSON

Match the Content-Type to the body format. Sensitive mutations also need the application's authentication, CSRF and authorisation controls.

Example and documentation
const response = await fetch("/example-api/preferences", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ theme: "system" })
});

Documentation: Browser and JavaScript documentation

Link to WEB-JS-010 · Back to entry index

WEB-JS-011

Cancelling stale requests

Abort an obsolete request when a newer action replaces it. Handle an intentional abort separately from a failure the reader needs to see.

Example and documentation
const controller = new AbortController();
const pending = fetch("/example-api/search?q=html", { signal: controller.signal });
controller.abort();
try { await pending; } catch (error) {
  if (error.name !== "AbortError") showFailure();
}

Documentation: Browser and JavaScript documentation

Link to WEB-JS-011 · Back to entry index

WEB-JS-012

Request time limits

Use a bounded timeout when waiting indefinitely would leave an interface stuck. Choose a duration appropriate to the operation and offer recovery.

Example and documentation
const response = await fetch("/example-api/topics", {
  signal: AbortSignal.timeout(8000)
});

Documentation: Browser and JavaScript documentation

Link to WEB-JS-012 · Back to entry index

WEB-JS-013

Independent results

AllSettled reports each outcome when independent operations may partially succeed. Process the result status before reading its value.

Example and documentation
const results = await Promise.allSettled([loadTopics(), loadBookmarks()]);
for (const result of results) {
  if (result.status === "fulfilled") useResult(result.value);
}

Documentation: Browser and JavaScript documentation

Link to WEB-JS-013 · Back to entry index

WEB-JS-014

Errors with a next step

Show a useful recovery action when a request fails. Keep technical details in appropriate diagnostics and preserve the reader's input.

Example and documentation
try { await loadTopics(); }
catch { status.textContent = "Topics could not load. Try again."; }

Documentation: Browser and JavaScript documentation

Link to WEB-JS-014 · Back to entry index

WEB-JS-015

Debounced input

Delay a repeated search briefly while typing, then replace the previous timer. Still support immediate form submission.

Example and documentation
let timer;
search.addEventListener("input", () => {
  clearTimeout(timer);
  timer = setTimeout(() => previewSearch(search.value), 250);
});

Documentation: Browser and JavaScript documentation

Link to WEB-JS-015 · Back to entry index

Data and formatting

WEB-JS-016

URLs and query parameters

Use URL and URLSearchParams to encode query values correctly. Preserve existing parameters unless the operation deliberately changes them.

Example and documentation
const url = new URL("/search", location.origin);
url.searchParams.set("q", "HTML & CSS");
location.assign(url.href);

Documentation: Browser and JavaScript documentation

Link to WEB-JS-016 · Back to entry index

WEB-JS-017

Parsing and validating JSON

Successful JSON parsing only proves syntax. Check the expected shape and types before using external data.

Example and documentation
const value = JSON.parse(rawText);
if (!value || !Array.isArray(value.items)) throw new Error("Invalid response shape");

Documentation: Browser and JavaScript documentation

Link to WEB-JS-017 · Back to entry index

WEB-JS-018

Local preferences

Use localStorage for small, non-sensitive preferences. Storage can fail, so handle access and parse errors with a usable default.

Example and documentation
let theme = "system";
try { theme = localStorage.getItem("theme") || "system"; }
catch { /* retain the default */ }

Documentation: Browser and JavaScript documentation

Link to WEB-JS-018 · Back to entry index

WEB-JS-019

Locale-aware numbers

Format amounts using an explicit locale and currency. Keep the numeric value separate from its displayed string.

Example and documentation
const format = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" });
const label = format.format(12.5);

Documentation: Browser and JavaScript documentation

Link to WEB-JS-019 · Back to entry index

WEB-JS-020

Dates and time zones

Choose the time zone that the displayed date represents. Use a consistent machine-readable source value instead of parsing ambiguous date strings.

Example and documentation
const format = new Intl.DateTimeFormat("en-GB", { dateStyle: "long", timeZone: "UTC" });
const label = format.format(new Date("2026-11-07T12:00:00Z"));

Documentation: Browser and JavaScript documentation

Link to WEB-JS-020 · Back to entry index

WEB-JS-022

Modules and explicit exports

Split reusable logic into modules with named exports. Keep private configuration on the server rather than embedding it in browser modules.

Example and documentation
// totals.js
export function total(price, delivery) { return price + delivery; }
// page.js
import { total } from "./totals.js";

Documentation: Browser and JavaScript documentation

Link to WEB-JS-022 · Back to entry index

Browser capabilities

WEB-JS-023

Media preferences

Use matchMedia to read a preference and listen for changes when behaviour must respond while the page is open.

Example and documentation
const preference = matchMedia("(prefers-reduced-motion: reduce)");
preference.addEventListener("change", () => setMotionEnabled(!preference.matches));

Documentation: Browser and JavaScript documentation

Link to WEB-JS-023 · Back to entry index

WEB-JS-024

Resize observation

Observe an element when behaviour depends on its size. Disconnect the observer when the component is no longer used.

Example and documentation
const observer = new ResizeObserver(([entry]) => {
  updateSize(entry.contentRect.width);
});
observer.observe(panel);

Documentation: Browser and JavaScript documentation

Link to WEB-JS-024 · Back to entry index

WEB-JS-025

Intersection observation

Use IntersectionObserver for work that depends on an element approaching the viewport. Provide a normal usable baseline while it waits.

Example and documentation
const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) if (entry.isIntersecting) showPreview(entry.target);
});
observer.observe(preview);

Documentation: Browser and JavaScript documentation

Link to WEB-JS-025 · Back to entry index

WEB-JS-026

Clipboard feedback

Clipboard writing generally requires a secure context and may fail. Run it from a deliberate action and report the result.

Example and documentation
copyButton.addEventListener("click", async () => {
  try { await navigator.clipboard.writeText(code.textContent); status.textContent = "Copied"; }
  catch { status.textContent = "Select and copy the text manually."; }
});

Documentation: Browser and JavaScript documentation

Link to WEB-JS-026 · Back to entry index

WEB-JS-027

Opening a native dialog

Use showModal for a modal dialog and keep a clear close action. Return focus to a useful control after closing when needed.

Example and documentation
openButton.addEventListener("click", () => dialog.showModal());
closeButton.addEventListener("click", () => dialog.close());

Documentation: Browser and JavaScript documentation

Link to WEB-JS-027 · Back to entry index

WEB-JS-028

Disclosure state

Read the open property of details when an enhancement needs the native disclosure state. The basic interaction works without a script.

Example and documentation
details.addEventListener("toggle", () => {
  status.textContent = details.open ? "Explanation expanded" : "Explanation collapsed";
});

Documentation: Browser and JavaScript documentation

Link to WEB-JS-028 · Back to entry index

WEB-JS-029

Animation frames

Schedule visual updates with requestAnimationFrame rather than an arbitrary fast timer. Cancel unnecessary work when the view is removed.

Example and documentation
const frame = requestAnimationFrame(() => {
  progress.style.transform = "scaleX(0.5)";
});
// If the update is no longer needed:
cancelAnimationFrame(frame);

Documentation: Browser and JavaScript documentation

Link to WEB-JS-029 · Back to entry index

WEB-JS-030

Progressive enhancement

Keep links, forms and reading content usable before adding optional JavaScript. A failed enhancement should leave a coherent route to the task.

Example and documentation
HTML baseline: a working link or form action
Enhancement: inline feedback or faster updates
Failure path: the baseline still completes the task

Documentation: Browser and JavaScript documentation

Link to WEB-JS-030 · Back to entry index

Continue learning

Reviewed . Send a correction through contact and corrections, including the entry number and supporting documentation.

How it works · DEX

Find, save and shop

Explore offers, save a shortlist and buy with the retailer.

More help and things to check

Confirm current prices and offer terms with the retailer. Device saves start in this browser. Account sync is optional.

Shopping tools & alerts
Household calendarYour For You findsWatch a priceAdd to Home Screen

Choose your deal alerts

Get selected updates about offers you save. You choose whether to enable notifications on this device.