3

I have a base plugin class I use as the basis of all my jQuery plugins. It is similar to the jQuery UI widget, but does a lot more heavy lifting for me.

I now wish to map data- attribute values, from the attached element, into any options passed to the plugin. This will allow the plugin to not only take the typical options object, but also allow data-driven override values on individual elements (a common requirement).

The problem I have is that my option properties are typically mixed case e.g. MaxHeight, but apparently the HTML specification only allows lowercase characters into data- attribute names.

As an example testbed: http://jsfiddle.net/TrueBlueAussie/tfkrwq09/1/

HTML:

<div id="test" data-DataTest="test2"></div>

jQuery:

var object = {
    DataTest: 123
};
$.each($('#test').data(), function (k, v) {
    object[k] = v;
});

console.log(object.datatest); // test
console.log(object.DataTest); // 123

Desired result:

console.log(object.datatest); // undefined
console.log(object.DataTest); // test

I am after ways to map data- attributes to mixed-case properties, while retaining the current speed and simplicity (if possible).

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • I did a quick test based on the example in jQuery's doc for `data()`, it seems that if you set the data yourself that jQuery will retrieve it as it was written. Example: `$('#test').data({TEST: 1});` and then do `console.log(object.TEST);` and you will get `1`. – SparoHawk Dec 18 '14 at 15:38
  • 1
    You have to use hyphen notation: `data-data-test="test2"` EDIT: in fact not for `DataTest` but that's quite why a property name shouldn't start with an uppercased letter – A. Wolff Dec 18 '14 at 15:38
  • This is interesting, didn't realize it worked that way. Not only does it seem that uppercase letters are invalid, they "All ... get ASCII-lowercased automatically" – brbcoding Dec 18 '14 at 15:38
  • Similar to this question: http://stackoverflow.com/questions/27359388/how-to-preserve-the-case-of-a-data-attribute – A. Wolff Dec 18 '14 at 15:39
  • @A. Wolff: Very close. `that's-a-great-solution`... Just tried `data--data-test` and also got a leading uppercase char... please post as answer :) – iCollect.it Ltd Dec 18 '14 at 15:42

1 Answers1

1

See following link regarding camelCased rule: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset

So in your case, i'd use:

<div id="test" data--data-test="test2"></div>

To get:

object.DataTest; //test2

A. Wolff
  • 74,033
  • 9
  • 94
  • 155