Skip to content

Instantly share code, notes, and snippets.

@andredublin
Forked from remy/html5-data.js
Created November 23, 2011 14:46
Show Gist options
  • Save andredublin/1388851 to your computer and use it in GitHub Desktop.
Save andredublin/1388851 to your computer and use it in GitHub Desktop.
data-* support
(function () {
var forEach = [].forEach,
regex = /^data-(.+)/,
dashChar = /\-([a-z])/ig,
el = document.createElement('div'),
mutationSupported = false,
match
;
function detectMutation() {
mutationSupported = true;
this.removeEventListener('DOMAttrModified', detectMutation, false);
}
function toCamelCase(s) {
return s.replace(dashChar, function (m,l) { return l.toUpperCase(); });
}
function updateDataset() {
var dataset = {};
forEach.call(this.attributes, function(attr) {
if (match = attr.name.match(regex))
dataset[toCamelCase(match[1])] = attr.value;
});
return dataset;
}
// only add support if the browser doesn't support data-* natively
if (el.dataset != undefined) return;
el.addEventListener('DOMAttrModified', detectMutation, false);
el.setAttribute('foo', 'bar');
Element.prototype.__defineGetter__('dataset', mutationSupported
? function () {
if (!this._datasetCache) {
this._datasetCache = updateDataset.call(this);
}
return this._datasetCache;
}
: updateDataset
);
document.addEventListener('DOMAttrModified', function (event) {
delete event.target._datasetCache;
}, false);
})();
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>test data-*</title>
<script src="data.js"></script>
</head>
<body>
<p data-id="ok" data-name="remy" data-screen-name="rem" id="hello">Hello World</p>
<script>
var el = document.getElementById('hello'), dl = el.dataset, a = [], key;
for (key in dl) a.push(key + ': ' + dl[key]);
alert(a.join('\n'));
a.length = 0;
el.setAttribute('data-foo', 'bar');
if (el._datasetCache) alert('Houston: we have a problem!');
dl = el.dataset;
for (key in dl) a.push(key + ': ' + dl[key]);
alert(a.join('\n'));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment