How To Make Cool Placeholder Text On HTML Form Input Boxes

Hover Label Input BoxOne of the cool tricks that I use frequently in my website designs is to make the labels of text input boxes in my HTML form appear to be on top of the input box itself then disappear when you click on it.

In the past I’ve tried achieving this by using labels and hovering them over the box, then making it display:none when you click on it.

The problem with this is that you either end up having to use a jQuery plugin to handle it or lots of extra code.

Recently I came across a method to have placeholder text disappear when you click on a text input box with very little code.

You’ll need jQuery installed, if you don’t know what that is you probably shouldn’t be doing this anyway.. let’s get stuck in.

First you setup your input box:

<input type="text" title="This is my placeholder text" class="usewatermark" />

Next, put this bit of jQuery code after your form:

<script type="text/javascript">
jQuery('.usewatermark').each(function(i, n) {
	var input = jQuery(n);
	input.val(input.attr('title'));
	input.addClass('watermark');
 
	input.focus(function() {
		if (jQuery(this).hasClass('watermark'))
			jQuery(this).val('').removeClass('watermark');
	});
 
	input.blur(function() {
		if ('' == jQuery(this).val())
			jQuery(this).val(jQuery(this).attr('title')).addClass('watermark');
	});
});
</script>

Styling your watermark

You can then use the “watermark” CSS class to style your placeholder text however you like.

I usually grey it out a bit and maybe make it italic or something along those lines.

Nice and simple and it uses very little code!

About Josh Kohlbach

Josh is a programmer, entrepreneur and the founder of Code My Own Road. He started this website to help programmers with business stuff and also to get things straight in his head. You can read more about Code My Own Road and Josh on the About page

4 Responses to How To Make Cool Placeholder Text On HTML Form Input Boxes

  1. Jordan February 20, 2013 at 10:24 pm #

    Another way to do it is use the HTML5 standard which works on all modern browsers with no JS:

    <input type=”search” placeholder=”search the internets” name=”query” />

    To support older browsers without changing the HTML:

    https://github.com/parndt/jquery-html5-placeholder-shim

    • Josh Kohlbach February 21, 2013 at 9:26 am #

      Hey Jordan, you’re right. I probably should have mentioned the new placeholder attribute, I have used it previously as well but only when compatibility with older browsers isn’t an issue. I usually design to IE7 backwards compatibility so the above snippet works on all browsers.

  2. olgri February 21, 2013 at 11:49 am #

    Great solution, Josh! Thanks!

Leave a Reply

Read more:
Self Promotion Isn't Evil

If you think self promotion is evil then you really shouldn't be in business for yourself. I was reading an...

Close