Coding Lesson

← All lessons

JavaScript: Interaction

Respond to a button

Lesson 12 of 18 · About 20 minutes

Your goal: Make a button change visible text.

Learn

JavaScript can find an element by its id. addEventListener runs a function when a click happens. textContent changes the element’s text.

View starter code
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My hobby page</title>
    <style></style>
  </head>

  <body>
    <h1>My hobby</h1>
    <p id="message">Ready to learn?</p>
    <button id="tip">Show a tip</button>
    <script>
      document.getElementById("tip").addEventListener("click", function () {
        document.getElementById("message").textContent = "Start with something small.";
      });
    </script>
  </body>
</html>

Your challenge

Change the message shown when the button is clicked.

Keep developing your hobby page: Download HTML before leaving the sandbox, then choose Open HTML file when returning to your project. Load saved draft restores only this lesson’s draft in this browser.

Practise in the sandbox
Show a hint

Edit the text inside the quotes after textContent =.

Show a sample answer

Try the challenge first. This is one possible answer or a snippet to adapt.

document.getElementById("tip").addEventListener("click", function () {
  document.getElementById("message").textContent = "Practise a little every day.";
});

Check your work

Nothing changes until you click; then your own tip appears.

Completion is your own check, not an automatic grade.