HTML says what is on the page. JavaScript lets the page react. The basic pattern is: find an element, listen for an event, then change something.
<button id="toggle">Show opening hours</button>
<p id="hours" hidden>Open every day, 9:00 to 18:00.</p>
<script>
const button = document.getElementById("toggle");
const hours = document.getElementById("hours");
button.addEventListener("click", function () {
hours.hidden = !hours.hidden;
button.textContent = hours.hidden ? "Show opening hours" : "Hide opening hours";
});
</script>
What happens
getElementByIdfinds the button and the paragraph by theiridvalues.addEventListener("click", ...)runs the function whenever the button is clicked.- Inside the function the paragraph’s
hiddenproperty is flipped, and the button text is updated.
Why ids and classes matter
This is why id and class exist. JavaScript uses them to find the elements it should change.
Use a button for actions
button element for things that do something on the page, not a link or a div. Buttons work with the keyboard by default.Exercise: a counter
Make a button that shows a number. Each click adds one to the number.
Show a possible solution
<button id="count">Clicked 0 times</button>
<script>
let n = 0;
const b = document.getElementById("count");
b.addEventListener("click", function () {
n++;
b.textContent = "Clicked " + n + " times";
});
</script>