Home / Shopping skills / Web development reference / Browser JavaScript reference 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 DOM and events Requests and asynchronous work Data and formatting Browser capabilities 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-001
Selecting elements Query the smallest useful document region and handle a missing match. A selector can legitimately find no element.
Example and documentation const heading = document.querySelector("h1");
if (heading) heading.textContent = "Reference notes";Documentation: Browser and JavaScript documentation
Link to WEB-JS-001 · Back to entry index
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
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 taskDocumentation: Browser and JavaScript documentation
Link to WEB-JS-030 · Back to entry index