Simple way to check if placeholder is supported?
Asked Answered
B

9

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!

Biparous answered 25/11, 2011 at 0:57 Comment(0)
S
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.)

Sora answered 25/11, 2011 at 1:0 Comment(14)
Thanks. Will try this... how does return ('placeholder in test') work? can you point me to a standard reference?Biparous
The in keyword returns true if the specified property is in the specified object. developer.mozilla.org/en/JavaScript/Reference/Operators/inSora
For better performance it's better to use hasOwnProperty if (document.createElement('input').hasOwnProperty('placeholder')) { /* ... */ }Trihedron
@Trihedron 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.Sora
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"Trihedron
@Trihedron 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! :-|Sora
test failed on IE9. @Nikitta answer is better.Seep
I believe you are mistaken, @jeff9888. Just ran this code on IE9 (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.Sora
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.Seep
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.Sora
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 falseKimes
IS there any reason not to use ('placeholder' in document.createElement('input'))?Assamese
@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).Sora
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…Ene
C
37

Or just:

if (document.createElement("input").placeholder == undefined) {
    // Placeholder is not supported
}
Cay answered 19/11, 2012 at 8:10 Comment(0)
M
8

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

if ('placeholder' in HTMLInputElement.prototype) {
    ...
}
Marsland answered 25/2, 2016 at 18:42 Comment(4)
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.Twentyfour
@Biparous Could you check this answer out? I think it better fits what you're trying to do in a performant way.Marsland
I get 'HTMLInputElement' is undefined in IE7Bryant
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.Creuse
E
6

If you are using Modernizr, quick catch following:

if(!Modernizr.input.placeholder){
  ...
}
Elaina answered 7/5, 2012 at 6:20 Comment(0)
E
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.

Erdda answered 25/11, 2011 at 1:1 Comment(0)
N
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.

Nickola answered 28/3, 2013 at 22:9 Comment(0)
B
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('');
            }
        })
    });
}
Banderilla answered 11/7, 2013 at 1:16 Comment(0)
G
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.

Graubert answered 15/6, 2015 at 13:21 Comment(0)
N
-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.

Nevernever answered 9/4, 2015 at 21:29 Comment(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.Scauper
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.Nevernever
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.Scauper
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"?Nevernever
The IE placeholder is working correctly. You are wrong. Case closed.Scauper
yes, sure, just because you call feature on bug - it become feature.Nevernever

© 2022 - 2024 — McMap. All rights reserved.