HTML5 I’m Using Today- Custom Data Attributes

I have two technology goals over the summer.

One is to finally do some meaningful Python work. I’ve been sniffing around Python for a couple of years now and still don’t have any real experience with it under my belt. Hopefully I can change that this summer.*

The other, more on-topic goal is to absolutely devour HTML5. I’ve had my eye on it from the dawn of the whatwg, but I’ve missed the recent opportunity we’ve been presented (in the form of browser support) to play with some of the new toys in a hands-on manner. That’ll change this summer.

And I’ll be sharing what I find, here.

See how well that works for all involved?

Anyway, one of the things I immediately gravitated to when reading through some of the documentation was the inclusion of custom data attributes. Obviously they’re not the sexiest new feature, but I’ve long used custom attributes in JavaScript, adding them at runtime to store all kinds of different data (for example, the initial height of a collapsed element, used to calculate later animations), so it’s really nice to see them wrapped into the specification. Being able to use them right in the HTML, in a standards compliant way, opens up all kinds of possibilities.

As proof of that, I’ve already started to use them. I’ve got a project I’m working on where I need to store certain data in order to write dynamic instances of the Permission TV player. Without going into too much detail as to why, it’s easiest if that data is written right into the HTML from the start. Before HTML5, I would have dumped the necessary info as content into the DIV to be rewritten by SWFObject and then read it out as needed. I don’t like that as is muddies the content. It comes across as nonsense to Google and to screen readers.

I don’t like nonsense.

Enter custom data attributes. Here’s what I came up with:

<ul>
<li class="video" data-PID="1137017" data-CID="1117632">
<div class="video-description"> This is a great video. It is so great. </div>
</li>

In JavaScript I then use getAttribute to grab the value, and then I make the magic happen.

[...]
var flashvars = {};
//video is a reference to the HTML object above with className "video"
flashvars.PID = video.getAttribute("data-PID");
flashvars.CID = video.getAttribute("data-CID");
[...]
swfobject.embedSWF("http://devkit.permissiontv.com/Preloader.swf", "flash-div", "470", "266", "9.0.0", "#000000", flashvars, params);

As you can see, it’s totally straightforward. Simply use the data- prefix and you’ve got a standards compliant way to embed custom data into your pages.

Hopefully everything about HTML5 will be that smooth.

*I’m about to launch into a redesign of my personal site, so I’m thinking that will present the needed opportunity.

Leave a Reply

Your email address will not be published. Required fields are marked *