Styling HTML5 Placeholder with CSS or jQuery

A quick tip to style the recently introduced HTML5 “Placeholder” attribute for input text and textarea elements via CSS or jQuery. The methods discussed have been tested successfully in all major browsers.

How to style a HTML5 Placeholder with CSS

With the advent of HTML5, the browsers now have the ability to replace one of the oldest JavaScript trick of “Placeholder” or “Watermark” text.

My primary focus today is on how to style the placeholder elements, most people make the mistake of selecting the whole input textbox with a placeholder attribute and this don’t give the expected result.

While the input text box’s placeholder attribute is widely supported by browsers today, most browsers have their own browser specific code to implement this. Given below are the most commonly used browser specific codes for styling the placeholder text.

Note : Opera 11-, Internet Explorer ( including IE9 ) doesn’t support placeholder attribute at all. How to fix this ?

input::-webkit-input-placeholder {
 /* - Code targeting webkit browsers go here - */
}
input:-moz-placeholder {
 /* - Code targeting Firefox (since v.4) goes here - */
}
input:-ms-input-placeholder {
 /* - Code targeting IE browsers (since v.10) goes here - */
}

jQuery fallback for HTML5 Placeholder

But what if you are targeting an older browser or one that doesn’t support placeholder text natively ? That’s where this nifty jQuery fallback comes in handy.

var a = document.createElement("input");
if ("placeholder" in a == false) {
	$("[placeholder]").focus(function() {
		var a = $(this);
		if (a.val() == a.attr("placeholder")) {
			a.val("").removeClass("placeholder");
			if (a.hasClass("password")) {
				a.removeClass("password");
				this.type = "password"
			}
		}
	}).blur(function() {
		var a = $(this);
		if (a.val() == "" || a.val() == a.attr("placeholder")) {
			if (this.type == "password") {
				a.addClass("password");
				this.type = "text"
			}
			a.addClass("placeholder").val(a.attr("placeholder"))
		}
	}).blur().parents("form").submit(function() {
		$(this).find("[placeholder]").each(function() {
			var a = $(this);
			if (a.val() == a.attr("placeholder"))
				a.val("")
		});
	});
}

Now simply add a class called “placeholder” in your style sheet and we are good to go!

3 Comments

Got something to say? Feel free, I want to hear from you! Leave a Comment

  1. Sancho Sunny says:

    brilliant !!

  2. Awesome How-To, have added to my favorites as I know I will need this at some point.

Trackbacks for this post

  1. girls things

Leave a Comment

Let me know your thoughts on this post but remember to place nicely folks!