Skip to content

Instantly share code, notes, and snippets.

@developit
Last active August 29, 2015 14:16
Show Gist options
  • Save developit/0b57e7a56a3ed15d5105 to your computer and use it in GitHub Desktop.
Save developit/0b57e7a56a3ed15d5105 to your computer and use it in GitHub Desktop.
Placeholders for all
<input tpl="url" placeholder="http://">
<script src="placeholder.js"></script>
<script>[].map.call(document.querySelectorAll('[placeholder]'), placeholder);</script>
(function() {
// default style
var s = document.createElement('style');
s.appendChild(document.createTextNode(s.textContent = '._placeholder { color:#CCC !important; }'));
(document.body || document.createElement('body')).appendChild(s);
function focus() {
var p = this.getAttribute('placeholder')
if (this.value===p) {
this.className = (this.className || '').replace(/ _placeholder(\s|$)/, '$1');
this.value = '';
}
}
function change() {
var p = this.getAttribute('placeholder');
this.className = (this.className || '').replace(/ _placeholder(\s|$)/, '$1');
if (!this.value) {
this.className += ' _placeholder';
this.value = p;
}
else {
this.value = '';
}
}
function hook(node, type, fn) {
(node.addEventListener ? node.addEventListener(type, fn) : node.attachEvent('on'+type, fn));
}
return function placeholder(node) {
if ('placeholder' in node || node.placeholderActive) return function(){};
node.placeholderActive = true;
hook(node, 'focus', focus);
hook(node, 'blur', change);
hook(node, 'change', change);
change.call(node);
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment