Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Forked from paulirish/html5-data.js
Created April 14, 2010 19:50
Show Gist options
  • Save rwaldron/366248 to your computer and use it in GitHub Desktop.
Save rwaldron/366248 to your computer and use it in GitHub Desktop.
(function (undefined) {
function detectMutation() {
mutationSupported = true;
this.removeEventListener('DOMAttrModified', detectMutation, false);
}
var forEach = [].forEach,
regex = /^data-(.+)/,
el = document.createElement('div'),
mutationSupported = false,
match
;
// only add support if the browser doesn't support data-* natively
if (el.datalist != undefined) return;
el.addEventListener('DOMAttrModified', detectMutation, false);
el.setAttribute('foo', 'bar');
Element.prototype.__defineGetter__('datalist', mutationSupported
? function () {
var datalist = {};
if (!this._datalistCache) {
forEach.call(this.attributes, function(attr) {
if (match = attr.name.match(regex))
datalist[match[1]] = attr.value;
});
this._datalistCache = datalist;
}
return this._datalistCache;
}
: function () {
var datalist = {};
forEach.call(this.attributes, function(attr) {
if (match = attr.name.match(regex))
datalist[match[1]] = attr.value;
});
return datalist;
}
);
document.addEventListener('DOMAttrModified', function (event) {
delete event.target._datalistCache;
}, false);
})();
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>test data-*</title>
<script src="html5-data.js"></script>
</head>
<body>
<p data-id="ok" data-name="remy" id="hello">Hello World</p>
<script>
var el = document.getElementById('hello'), dl = el.datalist, 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._datalistCache) alert('Houston: we have a problem!');
dl = el.datalist;
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