Skip to content

Instantly share code, notes, and snippets.

@avoidwork
Created December 2, 2011 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save avoidwork/1423758 to your computer and use it in GitHub Desktop.
Save avoidwork/1423758 to your computer and use it in GitHub Desktop.
(Proof of concept) Facade for HTML5 dataset attributes with fallback to data- attributes
/**
* Data attributes facade
*
* @type {Object}
*/
var data = {
/**
* Getter
*
* @param {Object} obj Element to query
* @param {String} key Data attribute key
* @return {String} Data attribute value
*/
get : function(obj, key) {
var value;
switch (true) {
case obj.hasOwnProperty("dataset") && key in obj.dataset:
value = obj.dataset[key];
break;
case obj.hasOwnProperty("data-" + key):
value = obj["data-" + key];
break;
default :
value = "";
}
return value;
},
/**
* Setter
*
* @param {Object} obj Element to receive data attribute
* @param {String} key Data attribute key
* @param {Mixed} value Data attribute value
* @return {Object} Data attribute value (for chaining values)
*/
set : function(obj, key, value) {
obj.hasOwnProperty("dataset") ? obj.dataset[key] = value : obj["data-" + key] = value.toString();
return value;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment