CHAPTER 56 · HTML

Templates and browser features: where HTML needs JavaScript

Reuse a small piece of markup and remember one harmless preference. Understand which jobs belong to HTML and which need browser features and JavaScript.

Download example files (ZIP)

A familiar starting point

A teacher keeps a blank study-card design and makes a copy for each lesson. A template serves a similar purpose: it holds markup for later use. The ordinary template contents are not displayed when the page loads. The template is not a visible card until code copies its contents into the page. It is not a secret place: visitors can inspect its source.

Read the template syntax

The opening <template id="card-template"> and closing </template> surround the draft. The id lets JavaScript find this template. Its content property provides a DocumentFragment: a small container of page nodes that is not itself a displayed element. CloneNode(true) makes a copy including the children. Appending the original content would move it; cloning keeps the draft available.

Do not put the same id into every repeated card. Id values must be unique in the displayed document. Our card uses an article, heading and paragraph with no repeated ids. An article is suitable here because the card is a small self-contained note.

The first script, one step at a time

Const gives a name to a value. GetElementById finds the template and button. AddEventListener waits for a click. The arrow function contains the steps to run after that click. QuerySelector finds a heading or paragraph inside the copy. TextContent puts plain text there. Append adds the copied nodes to the cards container.

Finally the script changes the visible status and disables the button. This exercise creates one card. The role=status paragraph lets assistive technology announce the changed message without moving keyboard focus. Reloading starts again because this program does not save the card.

What is a browser API?

An API is a set of ready-made features that code can ask to do a job. For example, browser storage can remember a small value. HTML describes a button; JavaScript listens for its click; the storage API performs the save. These are connected jobs, not extra HTML tags. You will study these features more deeply after learning JavaScript.

Local storage and session storage

LocalStorage stores string values under named keys. SetItem writes a value, getItem reads it and removeItem removes one key. SessionStorage has similar methods but belongs to a page session in a tab; reloading normally keeps it, while closing that tab normally ends it. Local storage can survive closing and reopening the browser, but settings, private browsing and clearing site data can remove it. Neither is a guaranteed backup.

An origin means the scheme, host and port together. HTTP and HTTPS versions of a site have different origins. Two different localhost ports also have different origins. Storage is shared by pages of the same origin; it is not a private store for one file. Other scripts running in that origin can access it. Do not put passwords, secrets or sensitive student details here.

Read the preference example

The key is a specific name owned by this exercise. The select offers links or forms. On load, the code accepts only those two saved values. Saving writes the selected string; forgetting removes only our key. It does not clear other applications' values. Try and catch mean: attempt these steps, and show a useful message if the browser reports a failure. Reading, writing or deleting can fail.

Run this example over local HTTP using the steps in Chapter 57. File-address storage behaviour varies between browsers. Choose Forms, save, reload and check the result. Then forget and reload. The preference is not sent to a server and will not appear on another device.

Other browser features: know their jobs first

FeatureJobWhat more is needed?
GeolocationAsk for a device locationA secure context, user permission and a useful denial path
Drag and dropMove or receive items through draggingJavaScript events and another usable way, such as buttons, for people who cannot drag
Web workerRun some JavaScript away from the page threadA worker script; it cannot directly edit the page DOM
FetchRequest data over a networkJavaScript, error handling and server permission rules for cross-origin access
Server-sent eventsReceive a stream of updates from a serverEventSource in JavaScript and a real server event stream
Service workerHandle selected requests and support features such as offline cachingA secure context and carefully managed installation, activation and caches

A secure context normally uses HTTPS; browsers also treat suitable localhost addresses as trustworthy for development. Availability still depends on the feature and browser. Adding a tag alone does not create live updates, offline support or location access. This course introduces the boundaries; a JavaScript course should teach the full implementations.

Try a small change

Change only the card heading string, save and reload, then add the card. The new heading should appear. Next change the storage status sentence without changing the key. The old saved preference should still load. This separates the displayed message from the stored value. The tutorial preview intentionally does not run these scripts; use the downloaded files.

Follow the idea

Copy a draft into the page
  1. 1Find the template
  2. 2Clone its content
  3. 3Fill the copy with text
  4. 4Append the copy

The template remains a reusable draft.

Complete program: template-card.html

Save this as template-card.html. Open it in your browser.

template-card.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Build a Study Card</title>
  </head>
  <body>
    <h1>Make one card from a template</h1>
    <main>
      <p>The template holds a draft. The button copies it into the page once.</p>
      <button type="button" id="add-card">Add study card</button>
      <div id="cards"></div>
      <p id="card-status" role="status">No card added yet.</p>
      <template id="card-template"
        ><article>
          <h2>Draft heading</h2>
          <p>Draft note</p>
        </article></template
      >
      <script>
        const template = document.getElementById('card-template');
        const button = document.getElementById('add-card');
        button.addEventListener('click', () => {
          const copy = template.content.cloneNode(true);
          copy.querySelector('h2').textContent = 'Link practice';
          copy.querySelector('p').textContent = 'Check where one relative link leads.';
          document.getElementById('cards').append(copy);
          document.getElementById('card-status').textContent = 'Study card added.';
          button.disabled = true;
        });
      </script>
    </main>
  </body>
</html>
Browser previewDocument title: Build a Study Card

This preview shows the example in a browser. Save the complete code in local files to test links between pages and downloads. Same-page section links work here. JavaScript does not run in this preview. Save the complete example and any named script file together to test its actions or canvas drawing in your browser.

Expected result in the saved file: initially there is no card. Add study card displays one Link practice article and a status message. The button then becomes disabled. Reloading removes the displayed card.

Complete program: stored-topic.html

Save this as stored-topic.html. Open it in your browser.

stored-topic.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Remember a Practice Topic</title>
  </head>
  <body>
    <h1>Save one fictional preference</h1>
    <main>
      <p>Use this over local HTTP. Saving is for this browser and origin, not a student account.</p>
      <p>
        <label for="saved-topic">Practice topic</label>
        <select id="saved-topic" name="topic">
          <option value="links">Links</option>
          <option value="forms">Forms</option>
        </select>
      </p>
      <button type="button" id="save-topic">Save topic</button>
      <button type="button" id="forget-topic">Forget topic</button>
      <p id="storage-status" role="status">No saved preference loaded.</p>
      <script>
        const key = 'resume-day-html-practice-topic';
        const select = document.getElementById('saved-topic');
        const status = document.getElementById('storage-status');
        try {
          const saved = localStorage.getItem(key);
          if (saved === 'links' || saved === 'forms') {
            select.value = saved;
            status.textContent = 'Loaded topic: ' + saved;
          }
        } catch {
          status.textContent = 'Storage is unavailable. You can still choose a topic.';
        }
        document.getElementById('save-topic').addEventListener('click', () => {
          try {
            localStorage.setItem(key, select.value);
            status.textContent = 'Saved topic: ' + select.value;
          } catch {
            status.textContent = 'Could not save. Browser storage may be blocked or full.';
          }
        });
        document.getElementById('forget-topic').addEventListener('click', () => {
          try {
            localStorage.removeItem(key);
            select.value = 'links';
            status.textContent = 'This practice preference was removed.';
          } catch {
            status.textContent = 'Could not remove the practice preference.';
          }
        });
      </script>
    </main>
  </body>
</html>
Browser previewDocument title: Remember a Practice Topic

This preview shows the example in a browser. Save the complete code in local files to test links between pages and downloads. Same-page section links work here. JavaScript does not run in this preview. Save the complete example and any named script file together to test its actions or canvas drawing in your browser.

Expected result over local HTTP: choose Forms and save. Reloading restores Forms if storage is available. Forget topic removes this exercise's preference only. If storage is blocked, a message explains the failure.

Problem and solution

Problem: a student puts a hidden template in the page and expects a finished list of cards.

Solution: distinguish the draft from the displayed copy. Find template.content, clone it, fill its plain text and append the copy to a visible container. Check the result before adding loops or more data.

Common mistakes and useful tips

  • A template does not display itself.
  • Use textContent for plain text instead of inserting supplied text as markup.
  • Avoid duplicate ids in copied cards.
  • Remove one owned key rather than calling localStorage.clear().
  • Keep a useful page when storage is blocked.

Practice questions

  1. Does a template appear automatically?
  2. Why clone instead of moving the draft?
  3. What does localStorage.getItem return for a missing key?
  4. Save Forms, reload, forget, then reload. What should be selected?
  5. Does saving here create a student account?
  6. Which feature would need a real server event stream?
Check your practice answers
  1. No. Its ordinary contents wait until code inserts a copy into the displayed document.
  2. A clone leaves the original template contents available for later copies.
  3. Null. Our example leaves the default topic selected.
  4. Forms after saving and reloading; Links after forgetting and reloading, if storage works.
  5. No. It saves one browser preference for this origin.
  6. Server-sent events; an HTML heading alone cannot produce live server updates.

Interview questions

What is the difference between HTML and a browser API?

HTML describes page structure and controls. A browser API exposes features that code can call, such as storing a value. They work together but are not the same language.

Why handle storage errors?

Browser policy, capacity and context can make storage unavailable. A useful page should explain the failure and still let the person continue.

Can a web worker directly change a heading?

No. A worker cannot directly access the page DOM. It can send a message back so page code can update the heading.

Is local storage suitable for passwords?

No. Scripts in the same origin can access it, and it is not a protected password store. This example saves only a harmless topic choice.

Quick revision

  • Template contents are a draft; clone before reuse.
  • Browser APIs need JavaScript and feature-specific handling.
  • Storage belongs to an origin and stores strings.
  • Handle failure and remove only your own key.