-
-
Save paulirish/362291 to your computer and use it in GitHub Desktop.
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
(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); | |
})(); |
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
<!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