HTML builds a page. CSS styles it. JavaScript makes it do things. Click a button and something changes; type in a box and something responds. That interactivity is what turns a document into an app. If you have not met JavaScript yet, begin with JavaScript for kids: first steps.
The big idea: events
An event is something that happens: a click, a key press, the mouse moving over something. JavaScript lets you say, "when this event happens, run this code." If your child has used Scratch's when this sprite clicked block, they already understand it. See Scratch concepts: loops, events and variables.
A button that changes text
Here is a complete tiny web page. Save it as index.html and open it in a browser.
<!DOCTYPE html>
<html>
<body>
<h1 id="message">Hello!</h1>
<button id="magic">Press me</button>
<script>
const button = document.getElementById("magic");
const message = document.getElementById("message");
button.addEventListener("click", function () {
message.textContent = "You pressed the button!";
});
</script>
</body>
</html>Let us decode it:
- Each HTML element has an
id, a unique name tag. document.getElementById("magic")finds the element with that name and stores it in a variable.addEventListener("click", ...)means "listen for a click on this button."- The function inside is what runs when the click happens.
message.textContent = ...changes the words in the heading.
Reading it out loud in plain English helps: "When the button is clicked, change the heading's text."
Making it a counter
Add a variable that remembers a number:
let count = 0;
button.addEventListener("click", function () {
count = count + 1;
message.textContent = "Clicks: " + count;
});Each press increases the count. This is the same variable idea from Python, as in what is a variable. Note that JavaScript uses let to create one.
Make it a decision
Mix in an if:
if (count === 10) {
message.textContent = "Ten clicks! Well done!";
}Triple equals === checks whether two things are equal, a close cousin of Python's ==.
Challenges to try
- Change the button so it toggles the heading between two messages.
- Make a button that changes the background colour:
document.body.style.backgroundColor = "gold";. - Add a second button that resets the counter to zero.
- Make a simple "magic 8 ball" that shows a random answer from a list of phrases each time you click.
Common stumbles
- A typo in the id. If nothing happens, check that the names match exactly.
- The script placed before the element. Put the
<script>at the bottom of the body, as above. - Missing brackets. Open the browser's console (usually F12) to see the red error text. How to read error messages explains how to use it.
JavaScript is a big language, but a button and a message are enough to feel like a real web developer. The JavaScript course takes the same ideas step by step.