Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check for native placeholder support in IE8

tldr: Why does ('placeholder' in inputElemnt) equal true in IE8 despite no native support for the placeholder attribute? Isn't (attribute in element) a good way to check for native support? The Javascript library Modernizer use it.

Long: I have a small Jquery plugin called Defaultvalue ( http://unwrongest.com/projects/defaultvalue/ ). I have a small Jquery plugin called Placeholder ( https://github.com/janjarfalk/jquery.placeholder.js ). It's basically a fallback for the HTML5 placeholder attribute.

In a recent updated I added these three lines of code. Hoping that Defaultvalue wouldn't run if the browser had native support for the placeholder attribute.

if('placeholder' in this){
    // this is an input-element
    return false;
}

It seems to work in most browsers except IE8 and IE7. For some reason it finds the key 'placeholder' in this, but there isn't, I think, any support for the placeholder attribute in IE7/IE8.

My code was inspired by this code in the Javascript library Modernizer ( http://www.modernizr.com/ ).

(function(props) {
    for (var i = 0, len = props.length; i < len; i++) {
        attrs[ props[i] ] = !!(props[i] in inputElem);
    }
    return attrs;
})('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));

What am I missing?

like image 378
u840903 Avatar asked Apr 04 '11 08:04

u840903


2 Answers

Creating a new raw input element solved my problem.

var nativePlaceholderSupport = (function() {
    var i = document.createElement('input');
    return i.placeholder !== undefined;
})();

if(nativePlaceholderSupport){
    return false;
}
var nativePlaceholderSupport = (function(){
    var i = document.createElement('input');
    return ('placeholder' in i);
})();

if(nativePlaceholderSupport){
    return false;
}

Thanks RobG, you led me to it.

like image 177
u840903 Avatar answered Oct 15 '22 17:10

u840903


It doesn't. It equals to false in both IE9 and IE8.

Live demo: http://jsfiddle.net/JVSgx/

like image 45
Šime Vidas Avatar answered Oct 15 '22 19:10

Šime Vidas