Simple way to check if placeholder is supported?

23,829

Solution 1

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

Solution 2

Or just:

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

Solution 3

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

if ('placeholder' in HTMLInputElement.prototype) {
    ...
}

Solution 4

If you are using Modernizr, quick catch following:

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

Solution 5

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.

Share:
23,829
algorithmicCoder
Author by

algorithmicCoder

Updated on February 26, 2020

Comments

  • algorithmicCoder
    algorithmicCoder over 4 years

    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!