Data in Elements
Sometimes an element needs to carry information that isn't its text. A button says Sea, but your code needs the color that goes with it. For this, HTML has data attributes: attributes whose name starts with data-, followed by a name you choose:
<button id="sea" data-color="teal">Sea</button>
<button id="sun" data-color="orange">Sun</button>The browser doesn't do anything with them; they're there for your script. JavaScript finds them in the element's property dataset, under their name without data-:
const seaButton = document.querySelector("#sea");
console.log(seaButton.dataset.color);tealTogether with event.target, this gives you one handler for many buttons, where each button says what should happen:
const title = document.querySelector("h1");
const seaButton = document.querySelector("#sea");
const sunButton = document.querySelector("#sun");
function paint(event) {
title.style.color = event.target.dataset.color;
}
seaButton.addEventListener("click", paint);
sunButton.addEventListener("click", paint);A click on Sea makes the heading teal, and a click on Sun makes it orange. Another color is just another button in the HTML, with its own data-color.
A few more things about data attributes:
- A name of several words, written with hyphens, is in camelCase in
dataset, as instyle:data-start-timeisdataset.startTime. - The value is always text. To calculate with
data-price="25", turn it into a number:Number(button.dataset.price). - When the element doesn't have the attribute, you get
undefined. - JavaScript can also set data attributes:
item.dataset.id = 7;gives the elementdata-id="7". That's handy for elements that your script creates.
Instructions
Write a function sayHello(event) that shows the greeting from the clicked button's data-hello in greeting. Make it the click handler of all three buttons. The Czech button then shows Ahoj.
Add a fourth language. In index.html, add a button with an id, the name of the language as its text and its greeting in data-hello, for example German with Hallo. In script.js, find the button and give it the same handler.