Testing for input placeholder support in Javascript 6/25/14
HTML5 brought us the ability to natively set placeholder values inside form inputs. However, we do need fallbacks for old browsers that don’t support the placeholder attribute, and that means checking for support with Javascript.
In this example, we’re going to hide the <label>
tag if the browser has placeholder support, otherwise display it normally1. We’ll do this by adding a class to the <html>
tag if the browser supports the placeholder attribute2. Then we can write CSS that only applies when that class exists.
Here’s the plain ol’ Javascript code for adding either a placeholder or no-placeholder class to the <html>
element depending on support:
What we’re doing with this code is creating an <input>
element3, and then checking to see if it has a placeholder property using Javascript’s hasOwnProperty method. Even if an element has no placeholder set or an empty placeholder, this will return true
when the browser supports the placeholder attribute4.
If you’re using jQuery, we can shorten the code a bit by using jQuery’s selector engine and addClass method:
With the Javascript in place we can use this bit of CSS and HTML:
In this case we’re only hiding labels that have the class hide-label and are inside a tag – in this case <html>
– with the class placeholder5.
Once all the code is in place, you should see these results depending on your browser:
-
If you need placeholders to work in old browsers, you can use Javascript to mimic the new native functionality. ↩
-
My first thought was to use Modernizr, but Modernizr doesn’t add classes to the HTML tag for input attribute support. ↩
-
Don’t worry, this input won’t be visible on the page unless we add it to the document using something like the appendChild method. ↩
-
Test this out on your own. Create an empty
img
tag and see if it supportssrc
. ↩ -
If we wanted to, we could also create styles that only apply when the no-placeholder class is present. ↩