Created
December 2, 2011 16:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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