53

I want to use the HTML5 "placeholder" attribute in my code if the user's browser supports it otherwise just print the field name on top of the form. But I only want to check whether placeholder is supported and not what version/name of browser the user is using.

So Ideally i would want to do something like

    <body>

     <script>

           if (placeholderIsNotSupported) {
             <b>Username</b>;
           } 
      </script>
    <input type = "text" placeholder ="Username">
</body>

Except Im not sure of the javascript bit. Help is appreciated!

9 Answers 9

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

I used a jQuery-ized version as a starting point. (Just giving credit where it's due.)

14
  • 1
    Thanks. Will try this... how does return ('placeholder in test') work? can you point me to a standard reference? Nov 25, 2011 at 1:11
  • 1
    The in keyword returns true if the specified property is in the specified object. developer.mozilla.org/en/JavaScript/Reference/Operators/in
    – Trott
    Nov 25, 2011 at 1:14
  • 1
    @iMoses IE8 and earlier have certain limitations to where hasOwnProperty is supported. I suspect that using hasOwnProperty in this context may break in IE8. Since we're doing feature detection here, I'm guessing that supporting older browsers is important to the person posting the question.
    – Trott
    Mar 19, 2013 at 14:03
  • 5
    @iMoses I just fired up the IE8 VM and checked. hasOwnProperty is unsupported in this context on IE8. It works on many objects, but not the object resulting from document.createElement('input'). Yay, browser quirks! :-|
    – Trott
    Mar 19, 2013 at 15:00
  • 2
    test failed on IE9. @Nikitta answer is better. Jul 5, 2013 at 3:06
37

Or just:

if (document.createElement("input").placeholder == undefined) {
    // Placeholder is not supported
}
0
8

Another way without making an input element in memory that has to be GC'd:

if ('placeholder' in HTMLInputElement.prototype) {
    ...
}
4
  • 1
    GC meaning garbage collected, so this should be faster.. also from the looks of it document doesn't have to be created yet, seems to be the superior answer. Jun 6, 2016 at 5:07
  • @algorithmicCoder Could you check this answer out? I think it better fits what you're trying to do in a performant way.
    – probablyup
    Jul 21, 2016 at 14:48
  • I get 'HTMLInputElement' is undefined in IE7
    – PapillonUK
    Apr 28, 2017 at 17:43
  • 1
    I used HTMLInputElement.prototype.hasOwnProperty("placeholder") instead, not sure if placeholders would work if they are part of chain or would it make performance any better.
    – Raimonds
    May 23, 2018 at 8:29
6

If you are using Modernizr, quick catch following:

if(!Modernizr.input.placeholder){
  ...
}
3

http://html5tutorial.info/html5-placeholder.php has the code to do it.

If you're already using jQuery, you don't really need to do this though. There are placeholder plugins available ( http://plugins.jquery.com/plugin-tags/placeholder ) that will use the HTML5 attribute where possible, and Javascript to simulate it if not.

2

I'm trying to do the same... here i wrote this

if(!('placeholder'in document.createElement("input"))){
   //... document.getElementById("element"). <-- rest of the code
}}

With this you should have an id to identify the element with the placeholder... I don't know thought if this also help you to identify the element ONLY when the placeholder isn't supported.

0

Hi there this is an old question but hopefully this helps someone.

This script will check the compatibility of placeholders in your browser, and if its not compatible it will make all input fields with a placeholder use the value="" field instead. Note when the form is submitted it will also change your input back to "" if nothing was entered.

// Add support for placeholders in all browsers
var testInput = document.createElement('input');
testPlaceholderCompatibility = ('placeholder' in testInput);
if (testPlaceholderCompatibility === false)
{
   $('[placeholder]').load(function(){
        var input = $(this);
        if (input.val() == '')
        {
            input.addClass('placeholder');
            input.val(input.attr('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().parents('form').submit(function() {
        $(this).find('[placeholder]').each(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
            }
        })
    });
}
0

A bit late to the party, but if you're using jQuery or AngularJS you can simplify the method suggested above without using any plugins.

jQuery

typeof $('<input>')[0].placeholder == 'string'

AngularJS

typeof angular.element('<input>')[0].placeholder == 'string'

The checks are very similar, as AngularJS runs jQlite under the hood.

-1

NOTE: Placeholder DO NOT work in internet explorer in a way, it should work.

document.createElement("input").placeholder == undefined

Doesnt work in internet explorer 11 - document.createElement("input").placeholder return empty string


var testInput = document.createElement('input');
testPlaceholderCompatibility = ('placeholder' in testInput);

Doesnt work in internet explorer 11 - return true


'placeholder'in document.createElement("input")

Doesnt work in internet explorer 11 - return true


In theory, Internet explorer 11 is supposed to support placeholder, but in fact - when input get focus placeholder disappear. In Chrome placeholder showed until you actually type something, no matter on focus. So, feature detection doesnt work in this case - you need to detect IE and show Labels.

6
  • ??? Just because IE11 handles placeholder differently than Chrome, doesn't mean it doesn't support placeholder. IE11 does support placeholder. The 3 code examples you give are working correctly in IE11.
    – Doug S
    May 4, 2015 at 6:37
  • In Chrome you can use small form with input without label (because placeholder is showed until some info is entered). In IE placeholder is removed as soon as input will get focus. In my case, input got focus on page load, so IE is sux. As always. May 5, 2015 at 9:11
  • That still doesn't mean it's broken. Everything is working correctly; you just don't like that way it works. Your answer is just wrong and completely misleading.
    – Doug S
    Jun 7, 2015 at 4:51
  • Do you want a bet - I can explain ANY bug with the same explanation - "It is working correctly, you just dont like that way it works"? Jun 25, 2015 at 16:15
  • The IE placeholder is working correctly. You are wrong. Case closed.
    – Doug S
    Jul 13, 2015 at 2:00

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.