HTML5 Placeholder Attribute

A guide to using the attribute, and support it for older browsers.


Placeholder

Placeholder text is a short example or hint text that is shown in a form field when the field is unfocused and has no input from the user. Designers like to use placeholders to make forms smaller, as smaller things appear to be simpler.

While the adding & removing of placeholder text on field focus has long been accomplished through JavaScript, there is now a placeholder attribute in the HTML5 working draft. Most modern browsers support the placeholder attribute and will automatically add/replace the placeholder text. They will also automatically exclude the placeholder from being sent when the form is submitted. However, versions of Internet Explorer prior to IE10 do not support the attribute.

<input type='text' name='email' placeholder='Email Address'/>

Supporting Older Browsers

It is very easy to detect placeholder support (or lack of) and duplicate the effect with a bit of JavaScript for older browsers.

<script>
    // placeholder polyfill
    $(document).ready(function(){
        function add() {
            if($(this).val() == ''){
                $(this).val($(this).attr('placeholder')).addClass('placeholder');
            }
        }

        function remove() {
            if($(this).val() == $(this).attr('placeholder')){
                $(this).val('').removeClass('placeholder');
            }
        }

        // Create a dummy element for feature detection
        if (!('placeholder' in $('<input>')[0])) {

            // Select the elements that have a placeholder attribute
            $('input[placeholder], textarea[placeholder]').blur(add).focus(remove).each(add);

            // Remove the placeholder text before the form is submitted
            $('form').submit(function(){
                $(this).find('input[placeholder], textarea[placeholder]').each(remove);
            });
        }
    });
</script>

To enable styling, this script adds a class of ‘placeholder’ while the placeholder text is being displayed.

Styling The Placeholder

Since placeholder has yet to be standardized, styles are applied through vendor-specific prefixes. Even though Opera 11 supports the placeholder attribute, it does not offer any way to style it at this time. It’s a good idea to go ahead and specify at least the color property to normalize the color between browsers. Otherwise, a default style will be provided which will vary from browser to browser.

::-webkit-input-placeholder { color:#999; }
:-moz-placeholder { color:#999; }
:-ms-input-placeholder { color:#999; }
.placeholder { color:#999; }

Unfortunately, the rules can not be combined into a single statement as a browser will not recognize vendor-specific selectors from other browser makers, resulting in an invalid rule that prevents the styles from being applied. John Catterfeld compiled a nifty list of CSS properties can be applied to placeholders.


Hey You

Follow me on Twitter, Github, or RSS. Why should you? I’m meticulous and have a lot of free time. Sometimes good things come out of that.

Comments

michael9 months agoReply
No need to self-close the <input> tag – this is HTML5, not XHTML5 🙂
Anonymous9 months agoReply
To be honest, I like self closing tags as a note that I do not need to match it when cleaning up.
Jack9 months agoReply
Michael is right of course, but since both are valid I appreciate the explicitness of the self-closing tag. It makes it very clear that there is no closing tag, and the omission of a closing tag is not a mistake. I don’t know if that is a good enough reason use them still, I may be stuck in the mindset after years of using XHTML.
Adam9 months agoReply
I like the tag and hate to come to just complain but the only problem here I can see is that your checker to see if the placeholder exists takes up more space than a javascript swap function for onfocus / onblur using a superfluous field like longdesc.

//Bind these by hardcoding them or if you're using JQuery do something fancy
function SwapOnFocus(obj) {
    if (obj.value == obj.title) {
        obj.value = '';
        obj.class = 'active'; /* JQuery has really nice class swaps or you could define a var baseInputClass and add to that here */
    }
}

function SwapOnBlur(obj) {
    if (obj.value == obj.title || obj.value == '') {
        obj.value = obj.title;
        obj.class = '';
    }
}

I always try to use the placeholder for example text instead of field names: http://mediamanifesto.com

Advertisements

18 comments on “HTML5 Placeholder Attribute

  1. Great – I should certainly pronounce, impressed with your web site. I had no trouble navigating through all the tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your customer to communicate. Nice task.

  2. Merely to follow up on the update of this subject on your website and would wish to let you know how much I prized the time you took to publish this useful post. Inside the post, you spoke regarding how to really handle this issue with all ease. It would be my pleasure to get some more ideas from your blog and come up to offer other people what I have benefited from you. Thanks for your usual terrific effort.

  3. I’ve been browsing online more than three hours as of late, yet I never discovered any interesting article like yours. It is beautiful price enough for me. Personally, if all web owners and bloggers made excellent content material as you did, the web will be a lot more useful than ever before.

  4. I believe that is one of the so much vital information
    for me. And i’m satisfied studying your article. But should observation on some general things, The web site taste is wonderful, the articles is actually great : D. Good activity, cheers

  5. of course like your web-site however you have to take
    a look at the spelling on quite a few of your posts.
    A number of them are rife with spelling problems and
    I in finding it very troublesome to tell the truth however I will surely come
    back again.

  6. Good day very cool web site!! Guy .. Excellent
    .. Superb .. I will bookmark your website and take the
    feeds also? I am happy to seek out so many helpful info here in the submit,
    we need develop more strategies in this regard, thanks for sharing.
    . . . . .

  7. הייתי רוצה להחריז לכם לבסוף איתרתי חברה שתבנה לחנייה שלי שערים מתרוממים , אחרי שחיפשתי החלטתי שאני רוכש את שער אצל חברת שערים היא חברה מקצועית ואיכותית . המסגרים שמייצרים שערים נגררים בחברה מסרו יחס חם . נתנו לי הסבר מפורט על מה אני משלם . לכן אם אתם במדינת ישראל וזקוקים לעסק בתחום מסגרות שמתמחה להתעסק אלומיניום התקשרו אליהם הם ממש טובים וגם המחיר הוגן .

  8. A lot of thanks for every one of your efforts on this site. Kate enjoys making time for investigations and it’s really obvious why. My spouse and i hear all of the powerful tactic you provide insightful guides by means of this web site and as well invigorate participation from other ones on the concern while our own child is now becoming educated a lot. Take advantage of the rest of the year. You’re doing a tremendous job.

  9. Thanks for the points you have shared here. Something important I would like to talk about is that computer system memory demands generally go up along with other advancements in the technology. For instance, when new generations of processors are made in the market, there is usually a corresponding increase in the type calls for of both the personal computer memory along with hard drive room. This is because software program operated through these cpus will inevitably rise in power to use the new technological innovation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s