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!

algorithmicCoder
  • 6,595
  • 20
  • 68
  • 117

9 Answers9

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.)

Maros
  • 1,825
  • 4
  • 25
  • 56
Trott
  • 66,479
  • 23
  • 173
  • 212
  • 1
    Thanks. Will try this... how does return ('placeholder in test') work? can you point me to a standard reference? – algorithmicCoder Nov 25 '11 at 01:11
  • 1
    The `in` keyword returns `true` if the specified property is in the specified object. https://developer.mozilla.org/en/JavaScript/Reference/Operators/in – Trott Nov 25 '11 at 01:14
  • For better performance it's better to use `hasOwnProperty` `if (document.createElement('input').hasOwnProperty('placeholder')) { /* ... */ }` – iMoses Mar 19 '13 at 13:35
  • 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 '13 at 14:03
  • I haven't checked myself, but according to MSDN: "Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards" – iMoses Mar 19 '13 at 14:12
  • 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 '13 at 15:00
  • 2
    test failed on IE9. @Nikitta answer is better. – Jeffrey Neo Jul 05 '13 at 03:06
  • I believe you are mistaken, @jeff9888. Just ran this code on IE9 (http://jsbin.com/ibubif/1/edit) and it worked without a problem. (It correctly reported that placeholder is not supported.) I used BrowserStack to test it in IE8, IE7, and IE6, and it worked in all of those as well. – Trott Jul 05 '13 at 04:40
  • 1
    Anyway, what I try IE9.0.8112 in Windows7, it return TRUE(but not supported actually), and it didn't show anything in the input value. – Jeffrey Neo Jul 05 '13 at 06:16
  • No problems in IE9 on Windows 7. Are you sure you copied the code correctly? Try running the jsbin at jsbin.com/ibubif/1/edit by going to jsbin.com/ibubif/1. In IE9, it will pop up an alert telling you that placeholder is not supported. – Trott Jul 05 '13 at 13:25
  • in IE10 `document.createElement('input').hasOwnProperty('placeholder')` returns false. In IE9: one line code returns true, but two line code (+saving created element into variable) returns false – blazkovicz Jan 08 '14 at 06:14
  • 1
    IS there any reason not to use `('placeholder' in document.createElement('input'))`? – Lars Ebert Jan 28 '14 at 08:59
  • 1
    @LarsEbert Reasons to not have it all on one line include readability/maintainability, reducing the likelihood of merge conflicts if you're working with others, and generally practicing good code habits. These are similar to the reasons to put it in its own function (although you can add code reuse to the list in that case). – Trott Jan 28 '14 at 23:28
  • In CoffeeScript, this should be `"placeholder" of test`. Note the "of" instead of "in". Otherwise it translated to a big chunk of JS that does not feature detect correctly… – Henrik N Sep 14 '15 at 16:41
37

Or just:

if (document.createElement("input").placeholder == undefined) {
    // Placeholder is not supported
}
Nikita Gavrilov
  • 527
  • 8
  • 13
8

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

if ('placeholder' in HTMLInputElement.prototype) {
    ...
}
probablyup
  • 7,636
  • 1
  • 27
  • 40
  • 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. – Joshua Robinson Jun 06 '16 at 05: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 '16 at 14:48
  • I get 'HTMLInputElement' is undefined in IE7 – PapillonUK Apr 28 '17 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 '18 at 08:29
6

If you are using Modernizr, quick catch following:

if(!Modernizr.input.placeholder){
  ...
}
beenhero
  • 61
  • 1
  • 2
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.

Michael Low
  • 24,276
  • 16
  • 82
  • 119
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('');
            }
        })
    });
}
Josh
  • 847
  • 9
  • 17
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.

Boaz
  • 19,892
  • 8
  • 62
  • 70
-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.

Andrew Zhilin
  • 1,654
  • 16
  • 11
  • ??? 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 04 '15 at 06: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. – Andrew Zhilin May 05 '15 at 09: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 07 '15 at 04: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"? – Andrew Zhilin Jun 25 '15 at 16:15
  • The IE placeholder is working correctly. You are wrong. Case closed. – Doug S Jul 13 '15 at 02:00
  • yes, sure, just because you call feature on bug - it become feature. – Andrew Zhilin Jul 24 '15 at 08:47