JavaScript: making pages do things
HTML structures a page. CSS styles it. JavaScript is the language that can change the page after it loads — when someone clicks a button, types in a field, or opens a menu.
What JavaScript is for
If you like writing the code yourself, you do not need a page builder or WordPress to make a page respond to a click. A short script in a simple HTML file is enough to start.
A browser already knows how to run JavaScript. Your script can:
- Listen for an event, such as a click.
- Find an element on the page, usually with an
id. - Change its text, show it, hide it, or toggle a class.
That is the core of a lot of front-end work. Forms, menus, and tabs are the same idea, built up in small steps.
A small, safe demo
The button below runs a script that is already on this page. It only changes the sentence next to it. Nothing is sent, stored, or evaluated from what you type — there is no text field here on purpose.
Try it
The mapletrail.example page is ready.
The same idea, written so you can type it yourself in a file:
<p id="status">The mapletrail.example page is ready.</p>
<button type="button" id="go">Change the message</button>
<script>
document.getElementById("go").addEventListener("click", function () {
document.getElementById("status").textContent =
"Hello from your script.";
});
</script>
addEventListener waits for the click. textContent replaces the words. Use textContent when you are putting plain words on the page. It will not treat the text as HTML.
Try it in a file on your computer
- Create a file named
index.htmlin a folder you control. - Add a heading, the paragraph and button from the snippet above, and the
<script>block just before the closing</body>tag. - Open the file in your browser. You do not need a server for this first test.
- Click the button. If the sentence changes, the script ran.
When you later publish the page, those same files go on a server, and a domain name points at them. That is covered in Publish your website and in Hosting Explained.
A note on safety: only run scripts you wrote, or that a person you trust wrote with you. Do not paste unknown code into a page to “see what it does.” This lesson does not run any code you type, and it does not load scripts from other sites.
Where to go next
Once a button can change text, you can practice other small, local changes: toggling a class, showing and hiding a paragraph, or checking that a field is not empty before you do anything with it. Keep the first scripts short, and keep the data on the page.
When the page is worth keeping, make a spare copy you control. See Make your own backups. You can host the finished site with us, or with any host you choose.