Last Updated: February 25, 2016
·
2.818K
· ipetepete

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!

http://jsfiddle.net/sn33kyp3t3/TWZg7/1/

6 Responses
Add your response

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)?

over 1 year ago ·

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?).

over 1 year ago ·

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").

over 1 year ago ·

@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 ;)

over 1 year ago ·

Wow!!! ... I didn't know I can create mine just like that.

over 1 year ago ·

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.

over 1 year ago ·