No-jQuery HTML5 placeholder fix

The “placeholder” attribute is a great new addition to HTML5, but it’s not supported in all  popular browsers (talking about you IE). I looked the web for a quick fix, but couldn’t find a polyfill, that didn’t require jQuery, so i decide to put one together myself.

<script type="text/javascript">
function hasPlaceholderSupport() {
  var input = document.createElement('input');
  return ('placeholder' in input);
}

if(!hasPlaceholderSupport()){
	var inputs = document.getElementsByTagName('input');
	for(var i=0,  count = inputs.length;i<count;i++){
		if(inputs[i].getAttribute('placeholder')){
			inputs[i].style.cssText = "color:#939393;font-style:italic;"
			inputs[i].value = inputs[i].getAttribute("placeholder");
			inputs[i].onclick = function(){
				if(this.value == this.getAttribute("placeholder")){
					this.value = '';
					this.style.cssText = "color:#000;font-style:normal;"
				}
			}
			inputs[i].onblur = function(){
				if(this.value == ''){
					this.value = this.getAttribute("placeholder");
					this.style.cssText = "color:#939393;font-style:italic;"
				}
			}
		}
	}
}
</script>

I took the very  nice check for placeholder support from David Walsh’s blog. Thanks David.

How to use?

You just put it at the bottom of your page just before the closing </body> tag, or you can call it inside window.onload.

Why no-jQuery?

I like jQuery very much, but i don’t want to load 70k just for placeholder polyfill,.. or to use $(‘document’).ready(); when there are very good replacements.