Use the data-force attribute, Luke
Its not widley known that you can arbitrarily set data attributes in your elements. Here is a little tip that might help with some slick widget templating.
The format is simply data-*:
<div id="thing" data-widget='{"status":"awesome","code":"thumbsup"}'>
So what?
Now you can do this:
var widgetData = $("#thing").data("widget");
if( widgetData.status === "awesome" )
haveAParty();
- beware of the quotes " vs ' will mess things up!
Written by Peter Peterson
Related protips
6 Responses

I didn't realize the jQuery .data() function automatically decodes JSON data. What does it do if non JSON data is used as the attribute (which is perfectly acceptable)?

It just treats it as text. I imagine one could hook up .data()'s internals to use another decoder, which might be neat in some cases (maybe convert space/comma-delimited list into an array?).

Note that $(el).data("key", "value") doesn't add a data-attribute to the HTML, it just modifies an internal jQuery array. If you're planning on modifying things then using the HTML elsewhere, you'll need $(el).attr("data-key", "value").

@reactiveraven but it modify the data API so you can make a .data('key') after this and get the good value. Even in another script ;)
Wow!!! ... I didn't know I can create mine just like that.

Beware jQuery.data also can treat content as integer so if your really need a number higher than a 32 bits integer, it will be truncated.
jQuery.attr('data-blabla') is safer if you need to deal with data integrity.