Create an Interactive Button with JavaScript

An interactive button is a small project that shows how HTML and JavaScript work together. HTML creates the button and message area; JavaScript listens for a click and changes the page.

Review the JavaScript explanation on Playcode123.com, then use the Sandbox to experiment with this example.

Build the button

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Interactive Button</title>
  <style>
    button {
      padding: 10px 16px;
      background: #0757a8;
      color: white;
      border: 0;
      border-radius: 6px;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <h1>Practice reminder</h1>
  <button id="reminderButton">Show reminder</button>
  <p id="message"></p>

  <script>
    const button = document.getElementById("reminderButton");
    const message = document.getElementById("message");

    button.addEventListener("click", function () {
      message.textContent = "Practice for 15 minutes today!";
      button.textContent = "Reminder shown";
    });
  </script>
</body>
</html>

Expected result

At first, the message area is empty. After you click the button, a reminder appears and the button label changes to “Reminder shown.”

How it works

  1. getElementById() finds the button and paragraph.
  2. addEventListener("click", ...) waits for a click.
  3. The function runs only after that click.
  4. textContent safely changes the visible text.

Why use addEventListener?

You may see onclick inside HTML examples. It works, but addEventListener() keeps the behavior in JavaScript and makes larger projects easier to organize.

Common mistakes

  • The ID in JavaScript does not exactly match the HTML ID.
  • The script runs before the button exists. Put the script near the end of <body> for this example.
  • "click" is misspelled or missing quotes.
  • The function is called immediately instead of being passed to the listener.
  • Smart quotation marks copied from formatted text replace normal code quotes.

Exercise: toggle the message

Add a variable named isVisible. On the first click, show the reminder. On the next click, clear it. Continue alternating each time the button is clicked. As an extra challenge, also change the button’s background color.

Check your work: click several times and watch the browser console for errors. Confirm that every ID and variable name uses the same capitalization.