What if I told you that it was possible for you to make an HTML attribute with any name you wanted, set to any value, while always being assured that it was valid code?

“Silly Dudley!” you might say. “That’s impossible! I know HTML5 is a lot looser than earlier versions of the language, but it’s not freeform poetry! You can’t just make up your own !”

Actually, you can. There are just two conditions:

  1. The attribute name has to start with data-
  2. The name you use has to follow web naming conventions.

That’s it. Still don’t believe me? Okay: fire up your editor of choice, make a valid HTML5 page, and enter this in the <body>:

<h1 data-holyHaleakala="big mojo">Heading 1</h1>

Then go ahead and validate that bad boy. I’ll wait.

Yes, it really works. Now that we’ve verified that fact, what’s it useful for? While the data attribute is being employed in systems like schema.org, and subsequent articles here will delve into practical code, I’ll provide a couple of examples:

Scenario 1

You have images on your site that could be inappropriate for work environments or children. You want to load those images onto the page, but not show them by default; instead, you’ll have the user indicate that they want to see them by using a toggle switch integrated into the UI of your site.

Solution

Create a data attribute with an appropriate name and value, and apply it to those particular images:

<img src="hot-koala-action.jpg" data-nsfw="true">

Then, in your CSS, use an attribute selector to turn them off by default:

img[data-nsfw=true] {
	display: none;
}

You could then use , CSS, or a combination thereof to make the NSFW images visible when the user indicated that they wished to see them.

Scenario 2

You have data displayed on your page in one measurement system, and want to allow the user to switch to another system on the fly. For example, you wish to convert between displaying metric and imperial measurements in body text on a web page.

Solution

Create a data attribute to record the type of measurement used. For example:

<p>I cycled <span data-measurement-type="km">103 kilometers</span> today.

Then use JavaScript to pick up a preference setting (stored as a cookie) and convert the units to display the appropriate system for the user.