HTML describes the elements on a page; JavaScript makes those elements respond to the reader. A <script> element adds JavaScript to the HTML so a button can change text without reloading the page.
An external .js file keeps the behavior separate from the markup. Its src path is resolved relative to the HTML file, so keeping both files in one folder makes the connection easy to follow.
Code that reads page elements must run after those elements exist. The defer attribute delays an external script until the HTML has been parsed, allowing a script in the head to attach a click handler to a button in the body.
Steps to add JavaScript to HTML:
- Create a file named index.html in your text editor with a button and a click count.
- index.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>JavaScript click counter</title> </head> <body> <h1>Click counter</h1> <button id="count-button" type="button">Count clicks</button> <p id="count" aria-live="polite">Clicks: 0</p> </body> </html>
The button and paragraph IDs let the script find those elements. The count starts at zero before any clicks.
- Create app.js in the same folder with the click handler.
- app.js
const button = document.querySelector("#count-button"); const count = document.querySelector("#count"); let clicks = 0; button.addEventListener("click", () => { clicks += 1; count.textContent = `Clicks: ${clicks}`; });
Each click increases the stored number and replaces the paragraph's text. The .js file contains JavaScript alone, without HTML <script> tags.
- Insert the script element immediately before </head> in index.html.
<script src="app.js" defer></script>The src="app.js" path points to the file beside index.html. With defer, the button and paragraph exist before the script selects them. The closing </script> tag is required even though the JavaScript is in another file.
- Save index.html and app.js as plain text with their exact file extensions.
A name such as app.js.txt will not match the script path.
- Open the saved index.html file in your browser.
The browser's Open file command or the file's local address opens the page directly; no web server is needed. The folder part of the address depends on where you saved the files.
- Click Count clicks once.

- Confirm that the text below the button changes from Clicks: 0 to Clicks: 1.
The changed count shows that the browser loaded app.js and ran its click handler. If the count stays at zero, a mismatched script filename, folder or element ID can prevent the handler from running.