Last active
August 29, 2015 14:16
-
-
Save developit/0b57e7a56a3ed15d5105 to your computer and use it in GitHub Desktop.
Placeholders for all
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
<input tpl="url" placeholder="http://"> | |
<script src="placeholder.js"></script> | |
<script>[].map.call(document.querySelectorAll('[placeholder]'), placeholder);</script> |
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() { | |
// 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