Form placeholders across browsers

HTML’s placeholder attribute is a nice think to use, but still many clients ask for IE 9 and even 8 support. That’s annoying from one side, but from another, you have a reason to charge a bit extra. However, let’s see how we can solveĀ those 8 and 9 disabilities.
Of course you would need jQuery (jQuery can be used as a solution to any problem) and Modernizr. Include those two, than get the jquery-placeholder plugin, few lines of code and you are good to go:

if(!Modernizr.input.placeholder){
	$('input, textarea').placeholder();
}

PS. this statement checks if the current browser supports placeholders, if it doesn’t – than it uses the jQuery plugin

If you think that including an entire jQuery plugin is an overkill, than you can just add this small script and call it a day:

$(document).ready(function(){

	if(!Modernizr.input.placeholder){

		$('[placeholder]').focus(function() {
		  var input = $(this);
		  if (input.val() == input.attr('placeholder')) {
			input.val('');
			input.removeClass('placeholder');
		  }
		}).blur(function() {
		  var input = $(this);
		  if (input.val() == '' || input.val() == input.attr('placeholder')) {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		  }
		}).blur();
		$('[placeholder]').parents('form').submit(function() {
		  $(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
			  input.val('');
			}
		  })
		});

	}
});

Credit goes to Nico Hagenburger

Leave a Reply

Your email address will not be published. Required fields are marked *