12 Apr 2011, 05:05
HTML5 data-* AttributesThe project that I’m currently working on had a requirement from the User Experience folks to have a button’s text change the first time it was clicked, and then on the second click, the intended action would be performed. One of the UI design guys on my team suggested adding some new classes that would serve as markers for the text that would be needed. Something like this:
<input class="switchTo-Buy_Now" type="button">
Technically, yes, that would work. And then you could bind some jQuery to the click event, parse out the last bit of the class, do some voodoo, and make it go. But, it’s ugly.
There’s got to be a better way! Enter HTML 5!
The HTML 5 spec contains support for data-*
attributes. That is, any attribute on any element that starts with data-*
is valid HTML 5 syntax, and is used to store data that doesn’t affect the layout, rendering, or function of the elements that it’s attached to. Finally we can hold any arbitrary data on any element and still have valid syntax!
Further, there’s support for this in jQuery core (as well as vanilla Javascript, but who really cares about that anymore anyway?).
So, we used to have some markup similar to this (which didn’t validate):
<input type="button" class="switchTo-Buy_Now" text="Buy Now!" />
And some jQuery a little something like this:
$("[class$=Buy_Now]").bind('click', function() {
var class = $(this).attr('class');
var switchTextId = class.substr(class.lastIndexOf('-')+1, class.length - class.lastIndexOf('-'));
var switchText = "";
if (switchTextId == "Buy_Now") {
switchText = "$4.99";
}
// Repeat that a lot. Or pull it off of some other
// non-standard attribute.
});
And NOW we have something like this (which is valid to boot!):
<input type="button" class="switchTo" data-switch-text="$4.99" text="Buy Now!" />
and a little jQuery action like this:
$('.buyTo')bind('click', function() {
var switchText = $(this).data('switch-text');
});
Pretty boss.