CKTIS / JavaScript
Finding an element by ID and reacting to document visibility
Find an element with `getElementById()`, read the page's current visibility with `document.hidden`, and update the interface on `visibilitychange`.
Version: Current web platform; runtime support varies
Syntax
// Browser DOM and HTML APIs; support depends on the browser, not on the ECMAScript edition.
document.getElementById(id) // Element | null
// Read-only visibility properties:
document.hidden // boolean
document.visibilityState // "hidden" | "visible"
// Register and later remove the same listener:
document.addEventListener("visibilitychange", handler)
document.removeEventListener("visibilitychange", handler)Document.getElementById/hidden/visibilitychange groups three distinct APIs. document.getElementById(id) takes the case-sensitive ID value, without a # prefix, and returns a matching Element in the document tree or null if none exists. IDs should be unique; duplicates return the first match in tree order. Look up the element after it has been inserted, and check the result before accessing properties: reading a property on null throws a TypeError.
document.hidden is a read-only boolean, equivalent to document.visibilityState === "hidden". The document state is "hidden" or "visible" and can change when you switch tabs, for example. It doesn't tell you whether a particular element is in the viewport or whether the page has focus. HTMLElement.hidden applies to an individual element and doesn't change the document's visibility state.
The browser fires visibilitychange at document after the state changes. It's a non-cancelable Event with no new-state payload; read the state from the document inside the handler. Register the handler and then call it once to initialize the UI. When tearing down a component, remove its listener from the same document with the same function and capture setting.
Pause unnecessary work while the document is hidden, but don't treat that state as proof of navigation away, user attention, or authorization. These are web platform APIs, not ECMAScript 2024 features. Runtimes without a browser DOM may not provide document, and support varies by runtime.
Examples
(() => {
function mount(document) {
const id = "cktis-page-visibility-status";
const status = document.createElement("p");
status.id = id;
document.body.append(status);
function render(event) {
const element = document.getElementById(id);
if (element === null) return;
element.textContent = document.hidden ? "hidden" : "visible";
if (event) console.log(element.textContent);
}
document.addEventListener("visibilitychange", render);
render();
console.log("ready");
}
if (typeof document !== "undefined") {
mount(document);
return;
}
// Node.js fixture: model only the document operations used above.
class TestDocument extends EventTarget {
#elements = [];
#hidden = false;
body = { append: (element) => this.#elements.push(element) };
createElement(tagName) {
return { tagName, id: "", textContent: "" };
}
getElementById(id) {
return this.#elements.find((element) => element.id === id) ?? null;
}
get hidden() {
return this.#hidden;
}
setHidden(hidden) {
if (this.#hidden === hidden) return;
this.#hidden = hidden;
this.dispatchEvent(new Event("visibilitychange"));
}
}
const testDocument = new TestDocument();
mount(testDocument);
testDocument.setHidden(true);
testDocument.setHidden(false);
})();Result
ready hidden visible
Paste the code once into the console of a fresh, active `about:blank` tab. Check for `ready`, switch tabs, wait briefly, and return. If the browser reports both transitions, the console logs `hidden` and then `visible`, and the paragraph reads `visible` again. Reload the tab to reset. To check the handler in Node.js, save the code as `main.js` and run `node main.js`; a test document simulates both transitions.
Related lessons
- JavaScript · Lesson 13 · Advanced · Version: 4