HTML5’s placeholder Attribute

By  on  

HTML5 has introduced many features to the browser;  some HTML-based, some in the form of JavaScript APIs, but all of them useful.  One of my favorites if the introduction of the placeholder attribute to INPUT elements.  The placeholder attribute shows text in a field until the field is focused upon, then hides the text.  You've seen this technique a billion times with JavaScript, but native HTML5 support is even better!

The HTML


You'll notice that all you need to do is add a placeholder attribute with the generic text of your choice.  Nice that you don't need JavaScript to create this effect, huh?

Checking for Placeholder Support

Since placeholder is a new capability, it's important to check for support in the user's browser:

function hasPlaceholderSupport() {
	var input = document.createElement('input');
	return ('placeholder' in input);
}

If the user's browser doesn't support the placeholder feature, you will need to employ a fallback with MooTools, Dojo, or the JavaScript toolkit of your choice:

/* mootools ftw! */
var firstNameBox = $('first_name'),
	message = firstNameBox.get('placeholder');
firstNameBox.addEvents({
	focus: function() {
		if(firstNameBox.value == message) { searchBox.value = ''; }
	},
	blur: function() {
		if(firstNameBox.value == '') { searchBox.value = message; }
	}
});

placeholder is another great addition to the browser and replaces the oldest snippet of JavaScript in the book! You can event style HTML5 placeholders!

Recent Features

  • By
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

Incredible Demos

  • By
    Display Images as Grayscale with CSS Filters

    CSS filters aren't yet widely supported but they are indeed impressive and a modern need for web imagery.  CSS filters allow you to modify the display of images in a variety of ways, one of those ways being displaying images as grayscale. Doing so requires the...

  • By
    NSFW Blocker Using MooTools and CSS

    One of my guilty pleasures is scoping out the latest celebrity gossip from PerezHilton.com, DListed.com, and JoBlo.com. Unfortunately, these sites occasionally post NSFW pictures which makes checking these sites on lunch a huge gamble -- a trip to HR's office could be just a click away. Since...

Discussion

  1. I would use MooTools OverText instead of setting it as value… My example: http://jsfiddle.net/fabian/8Zacd/ – just a quick showcase.

  2. You can apply css to it via input::-webkit-input-placeholder – But anyone know how to do this for firefox/opera?

    • Roberto

      for mozilla:
      :-moz-placeholder

  3. Note that I used to have problems with placeholder in Safari 4. It reports to support placeholder but it really doesn’t.

  4. @Adam I’d suggest using blur/focus to add/remove a class with the appropriate styles. There is an ongoing discussion on the naming of the property for firefox

  5. @Christoph Pojer: thanks for the helpful extra info :)

  6. Thanks bro! HTML5 & Mootools FTW!!!

    p.s. is it an idea for the mootools core to create the HTML5 elements on the fly for IE?

  7. You can check placeholder support in web browsers here: http://www.fanatical.pl/wp-content/uploads/2010/08/formularz.html

    Chrome and Safari – OK.

  8. Don’t forget to clear the DIY placeholder on form submit otherwise your users will get confusing validation messages! I don’t know MooTools, but jQuery might look like this:

    $('form input[type="submit"]').bind('click', function() {
    	$('form input[type="text"]').each(function() {
    		var $field = $(this);
    		if ($field.val() == $field.attr('placeholder')) {
    			$field.val('');
    		}
    	});
    	return true;
    });
  9. Support for the placeholder attribute is very lacking from what i’ve seen.

    • While that may be true, there’s nothing wrong with taking advantage of placeholder now!

  10. Your javascript placeholder workaround would still send the placeholder value if the form is submitted, instead of sending a empty string. jQuery Sparkle contains another graceful script for this with form support:
    http://www.balupton.com/sandbox/jquery-sparkle/demo/#sparkle-demo-hint

  11. Any idea if it’s possible to style the placeholder text? Currently it’s a default grey in most browsers, but if you style your inputs that can quickly become unreadable.

    Eg if I style my inputs to have a light grey background, or if the input text is styled to be the same light grey…

  12. @ben just read the comments above.

  13. iams

    I’m using the newest version of firefox and the demo doesn’t work, just an empty text box

    • Firefox has yet to implement placeholder.

    • iams

      ahh, thanks
      figured they’d be ahead of the curve

      html5 is a great thing unfortunately it’s going to take some time for the browsers (and people updating their browsers) to catch up

    • It’s coming in Firefox 3.7

  14. I finally got around to release my Form.Placeholder implementation: http://github.com/cpojer/mootools-form-placeholder

  15. I like placeholders, but what about password fields placeholders?
    IMHO it doesn’t make sense to hide also the placeholder, browsers should show the placeholder and hide the password.

  16. I used the html5 placeholder attributes, it was surprisingly easy. The only thing that really bugs me is compatibility with IE6. I used Modernizr to do all the feature checks, now it’s working really good.

  17. YaNIV

    in the article you say the place holder will disappear on focus
    in your demo – it disappears on keydown.
    is there a way in HTML5 to get that functionality as well or i need to write a JS for it.

  18. Thanks for the tip. I wound up using something a little different. Instead of putting text in the field I used jQuery to append the value of the placeholder attribute into a paragraph tag right before the input field in the DOM.

    The $.support snippet got the ball rolling.

  19. Your code refers to firstNameBox and then searchBox, you may want t fix that.

  20. dnc

    So now when you have placeholder attribute, instead to just write javascript function that handles placeholder text you have to write both, the placeholder attribute/value (in case your browser supports it) and javascript placeholder handling (otherwise). On the top of that you need to check if the browser supports it which additionally complicates your presentation logic. Great!

  21. Helped me – thanks! :-)

  22. ironarm

    Makes me laugh that people have to use a library for something this simple; monkeys. Do it yourself and learn. You should only use libraries for complex things that you can handle instead of using libraries for everything. Even then you should try it at least once. I won’t write my own calendar, but i’ll definitely write my own placeholder code, for god sake.

  23. I wrote a jQuery plugin to support placeholder text on older browsers. It’s hosted on GitHub and you can download the latest here: https://github.com/robvolk/jQuery.InputHints
    Example code and demo: http://robvolk.com/jquery-form-input-hints-plugin/

  24. for opera -o-placeholder

  25. Dave – Thanks for this. You have come to my rescue several times now. It’s appreciated.

  26. Adam Moore

    Good article, but a lot of things are not clarified here, I would recommend to read this one to know more about it: http://basicuse.net/articles/pl/textile/html_css/html5_placeholder_attribute_with_cross_browser_support

  27. placeholder is a problem on safari, Maxthon, android browser … maybe in feature it dont be a problem,

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!