Created
February 28, 2012 02:45
-
-
Save draeton/1928836 to your computer and use it in GitHub Desktop.
Get HTML5 data attributes with no type coercion
This file contains hidden or 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
/** | |
* jQuery.readDataAttr | |
* | |
* Gets html5 data attributes without type coercion. | |
* If called with no parameters, returns an object with all | |
* current data-* values. | |
* | |
* @param {String} [key] Optional; if set, return only this | |
* value | |
* @return {*} Return either all values, or the value at key | |
*/ | |
(function (window, $) { | |
"use strict"; | |
var slice = Array.prototype.slice; | |
var cache = {}; | |
var uuid = 0; | |
var expando = "jQueryReadDataAttr" + (+new Date()); | |
var dataTest = /^data-/; | |
var readDataAttr = function (elem) { | |
var id = elem[expando]; | |
var data = cache[id]; | |
var attrs, attr, i, l, key; | |
if (!$.isPlainObject(data)) { | |
attrs = slice.call(elem.attributes); | |
data = {}; | |
for (i = 0, l = attrs.length; i < l; i++) { | |
attr = attrs[i]; | |
if (dataTest.test(attr.name)) { | |
key = attr.name.replace(dataTest, ""); | |
key = $.camelCase(key); | |
data[key] = attr.nodeValue; | |
} | |
} | |
id = uuid++; | |
cache[id] = data; | |
elem[expando] = id; | |
} | |
return data; | |
}; | |
$.fn.readDataAttr = function (key) { | |
var elem = $(this).get(0); | |
var data = readDataAttr(elem); | |
if (typeof key !== "undefined") { | |
key = $.camelCase(key); | |
data = data[key]; | |
} | |
return data; | |
}; | |
$.readDataAttr = function (elem, key) { | |
return $(elem).readDataAttr(key); | |
}; | |
}(window, jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment