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 attributes!”
Actually, you can. There are just two conditions:
- The attribute name has to start with
data-
- 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. You can even data
as an element:
<data>content</data>
Now that we’ve verified that fact, what are the data tag and attribute useful for? While articles here will delve into practical code, I’ll provide an example in this one:
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 JavaScript, CSS, or a combination thereof to make the NSFW images visible when the user indicated that they wished to see them.
Photograph by NATS Press Office, used under a Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic license
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.