CHAPTER 46 · HTML

HTML and JavaScript: connect a small behaviour to a page

See what script does, load a local JavaScript file and explain one button action. Keep useful HTML available when the action cannot run.

Download example files (ZIP)

Content, appearance and behaviour

A classroom notice can contain information, use readable lettering and have an action such as opening another sheet. On the web, HTML describes content, CSS presents it and JavaScript can add behaviour. A script is code the browser can execute. A button does not invent an action just because it looks clickable.

Java and JavaScript are different languages despite their names. This chapter introduces the HTML connection and one small example; you do not need to learn all JavaScript before understanding where the code belongs.

Script can contain code or identify a file

An inline script holds code between opening and closing script tags. An external script uses src to identify a .js file. Unlike img, script needs its closing tag. Do not put fallback JavaScript between the tags of a script that already has src.

HTML fragment — part of a document
<script src="practice-message.js" defer></script>

Src is a file address, just as it is for other resources. The external file contains JavaScript only, without script tags or an HTML document wrapper. Our examples use plain classic scripts, so type=text/javascript is unnecessary.

Run code after its elements exist

A script that looks for a button before the browser has read that button can fail to find it. The first complete program places its inline script after the paragraph and button. The second puts an external script in head with defer.

For a classic external script, defer downloads while HTML is being read and runs after the document has been parsed, before DOMContentLoaded. Deferred classic scripts retain their document order. Async is different: it runs when ready and does not guarantee that same order. Defer does not delay an ordinary inline classic script. Module scripts have their own loading rules and are deferred by default unless async changes their behaviour. DOMContentLoaded is the browser event that signals that the HTML has been read into the document and deferred scripts have finished.

Read the first two JavaScript lines

Document represents the current document to the script. GetElementById looks up an element by its unique id. The ids show-message and practice-message match the button and paragraph in HTML. The two const statements give us names for those element references.

Quotes delimit text strings. A semicolon ends each statement here. These lines find existing elements; they do not create new controls. Changing an id in HTML without changing the lookup is a common reason for a broken example.

Read the action without memorising it

AddEventListener connects a response to an event. Click is the event name. Function () { ... } is the group of instructions to run when that event occurs. Inside it, textContent replaces the paragraph text with the new reminder.

TextContent treats the new value as text rather than interpreting it as HTML. Do not replace this simple text update with untrusted innerHTML. The button is type=button so it will not accidentally submit a form if the example is later placed in one. Native buttons can also be activated from a keyboard.

A changing sentence needs a clear context

The paragraph begins with a useful reminder instead of being empty. Aria-live=polite asks assistive tools to announce its update when appropriate without immediately interrupting the current announcement. It does not move focus. Screen-reader and browser combinations still need real testing.

If JavaScript is disabled, noscript can show its alternative. A failed download or a runtime error does not automatically activate noscript, so the ordinary visible reminder remains useful too. Our tutorial preview deliberately disables scripts and says so; save the complete files to run the action.

Save the external file

Save this as practice-message.js beside linked-message.html. Open the HTML page; do not try to run the JavaScript file by double-clicking it as a web page.

practice-message.js
const button = document.getElementById('show-message');
const message = document.getElementById('practice-message');
button.addEventListener('click', function () {
  message.textContent = 'Check the filename, save the page and refresh the browser.';
});

Click or keyboard-activate the button. The paragraph should change once and retain that text on later clicks. Refreshing starts again from the saved HTML. The example does not store a preference or send data anywhere.

Debug the connection one step at a time

If the button does nothing, check the filename, folder, saved changes and id spellings. Browser developer tools can show a missing script request or a JavaScript error. A typo is information to investigate, not proof that you cannot learn.

Load scripts from sources you understand and trust. A script is executable code, not a harmless decoration. Keep the page useful with ordinary headings, links and visible information rather than depending on a script for every sentence.

Follow the idea

Connect one action
  1. 1Find existing elements by id
  2. 2Listen for a button activation
  3. 3Update the reminder as text
  4. 4Keep the initial HTML useful

The saved files run the script; the isolated preview does not.

Complete program: inline-message.html

Save this as inline-message.html. Open it in your browser.

inline-message.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>A Small Inline Script</title>
  </head>
  <body>
    <h1>Show a practice reminder</h1>
    <main>
      <p id="practice-message" aria-live="polite">Save your work before testing a change.</p>
      <button type="button" id="show-message">Show the next reminder</button>
      <noscript><p>The button needs JavaScript. You can still use the reminder above.</p></noscript>
      <script>
        const button = document.getElementById('show-message');
        const message = document.getElementById('practice-message');
        button.addEventListener('click', function () {
          message.textContent = 'Check the filename, save the page and refresh the browser.';
        });
      </script>
    </main>
  </body>
</html>
Browser previewDocument title: A Small Inline Script

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 a saved file: activate Show the next reminder and the paragraph becomes Check the filename, save the page and refresh the browser. The embedded tutorial preview shows the initial content and a scripts-disabled notice instead.

Complete program: linked-message.html

Save this as linked-message.html. Open it in your browser.

linked-message.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Load a Local JavaScript File</title>
    <script src="practice-message.js" defer></script>
  </head>
  <body>
    <h1>Connect a separate script</h1>
    <main>
      <p id="practice-message" aria-live="polite">Save your work before testing a change.</p>
      <button type="button" id="show-message">Show the next reminder</button>
      <noscript><p>The button needs JavaScript. You can still use the reminder above.</p></noscript>
    </main>
  </body>
</html>
Browser previewDocument title: Load a Local JavaScript File

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: save practice-message.js beside this HTML file, then open the HTML. The same button action works using the external script. A missing script file leaves the initial reminder visible; it does not make noscript appear automatically.

Problem and solution

Problem: a button stopped working after its id changed.

Solution: compare the HTML id with getElementById. Repair the matching value, save both files and reload. Check the browser console if the action still fails.

Common mistakes and useful tips

  • Close script even when it has src.
  • Do not put script tags inside a .js file.
  • Do not assume async preserves execution order.
  • Defer on an inline classic script does not postpone it.
  • Keep useful ordinary content when scripts fail.
  • Use textContent for this text-only update.

Practice questions

  1. What does src identify on script?
  2. Why is the first inline script after the button?
  3. What does defer do for the external classic script?
  4. Does noscript appear whenever a script download fails?
  5. Why use type=button?
  6. Save both versions and activate their buttons with Enter or Space. Then reload. What changes?
Check your practice answers
  1. The external script file address.
  2. The relevant elements exist before the lookup runs.
  3. It runs after HTML parsing and preserves order with other deferred classic scripts.
  4. No. It relates to scripting being disabled or unsupported, not every runtime or download failure.
  5. The control performs an action rather than submitting a form.
  6. The paragraph changes after activation. Reload restores its saved initial text; no state is stored.

Interview questions

How do HTML and JavaScript differ?

HTML describes document content and meaning. JavaScript supplies executable behaviour such as responding to a button.

How do defer and async differ?

For classic external scripts, defer waits for parsing and keeps order. Async runs when its download is ready, so order and document readiness differ.

Why choose textContent for a reminder?

The value is ordinary text. It does not need HTML interpretation, and treating it as text avoids unintended markup insertion.

What should remain if an optional action fails?

The page should retain useful visible information and a clear route through its main task, rather than presenting an empty page.

Quick revision

  • Match the file path and ids.
  • Load code at the right point.
  • Explain an action before adding it.
  • Test saved files and keep a useful fallback.