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 normally
<html>
tag if the browser supports the placeholder attributeHere’s the plain ol’ Javascript code for adding either a placeholder or no-placeholder class to the <html>
element depending on support:
var htmlEl = document.getElementsByTagName('html');
htmlEl = htmlEl[0]; // first result is the html tag
var inputTest = document.createElement('input');
if( inputTest.hasOwnProperty('placeholder') ) {
htmlEl.className += ' ' + 'placeholder';
} else {
htmlEl.className += ' ' + 'no-placeholder';
}
What we’re doing with this code is creating an <input>
element
true
when the browser supports the placeholder attributeIf you’re using jQuery, we can shorten the code a bit by using jQuery’s selector engine and addClass method:
var inputTest = document.createElement('input');
if( inputTest.hasOwnProperty('placeholder') ) {
$('html').addClass('placeholder');
} else {
$('html').addClass('no-placeholder');
}
With the Javascript in place we can use this bit of CSS and HTML:
<style>
.placeholder .hide-label { display: none; }
</style>
<label class="hide-label" for="your-name">Your Name</label>
<input type="text" name="your-name" id="your-name">
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 placeholder
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. ↩