vd-ncq
Last Updated: February 25, 2016
·
2.594K
· 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

1021

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 ·
1022

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 ·
1023

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 ·
1026

@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 ·
1084

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

over 1 year ago ·
1346

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 ·