A row of buttons can share the same behavior even when each button has a different value to look up. An HTML data attribute stores that value on the button, so JavaScript can show the pickup counter for the item a visitor chooses.

JavaScript reads custom attributes through the element's dataset property. Hyphens between words become camel case, so data-pickup-counter becomes dataset.pickupCounter. The value is a string.

Anyone who can inspect the page can read its data attributes before interacting with it. Store values that are safe for visitors to see, such as pickup locations.

Steps to use HTML data attributes:

  1. Create pickup.html in a new test folder using your text editor.
    pickup.html
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Pickup counters</title>
      <style>
        body {
          margin: 2rem;
          font: 24px system-ui, sans-serif;
        }
        button {
          font: inherit;
          padding: 0.4em 0.7em;
        }
      </style>
    </head>
    <body>
      <h1>Pickup counters</h1>
      <p>
        Pickup counter:
        <output id="pickup-counter">
          Choose an item
        </output>
      </p>
    </body>
    </html>
  2. Insert these item buttons between the heading and the pickup counter paragraph.
      <button type="button"
        data-pickup-counter="Counter A">
        Desk lamp
      </button>
      <button type="button"
        data-pickup-counter="Counter B">
        Floor lamp
      </button>

    Both buttons use the same attribute name, data-pickup-counter. The value in quotes is the counter for that item.

  3. Insert the script just before the closing </body> tag.
      <script>
        const output =
          document.querySelector("#pickup-counter");
        const buttons = document.querySelectorAll(
          "button[data-pickup-counter]"
        );
     
        for (const button of buttons) {
          button.addEventListener("click", () => {
            output.textContent =
              button.dataset.pickupCounter;
          });
        }
      </script>

    Each listener reads dataset.pickupCounter from its own button. Setting textContent displays that string as plain text.

  4. Save pickup.html.
  5. Open the saved pickup.html in desktop Chrome.
  6. Click Desk lamp.
  7. Verify that Pickup counter reads Counter A.
  8. Click Floor lamp.
  9. Verify that Pickup counter changes to Counter B.
Share this guide