Search code examples
javascriptinternet-explorer-8conditional-operatorbrowser-detection

Detecting IE8 with JavaScript using document.addEventListener


I came across this code in a project I am working on that is used to detect if the browser is IE8:

var isIE8 = function(){ return (!document.addEventListener) ? true : false; };

I don't understand why the conditional operator ? true : false is used to return true if true and false if false. The logical NOT ! is applied to the value of document.addEventListener and will always return a Boolean value, would this not do exactly the same thing:

var isIE8 = function(){ return (!document.addEventListener); };

.addEventListener Browser Compatibility

This Answer was the closest information I could find on this.

Thanks for taking a look :)


Solution

  • If you would just like to detect IE8, checking for addEventListener will do the job. But if you would like to check for IE and its versions in general, I find this method the most intuitive and most useful:

    var uA = navigator.userAgent;
    var browser = null;
    var ieVersion = null; 
    
    if (uA.indexOf('MSIE 6') >= 0) {
        browser = 'IE';
        ieVersion = 6;
    }
    if (uA.indexOf('MSIE 7') >= 0) {
        browser = 'IE';
        ieVersion = 7;
    }
    if (document.documentMode) { // as of IE8
        browser = 'IE';
        ieVersion = document.documentMode;
    }
    

    You're also catching higher IE versions in Compatibility Mode/View this way. And using the script is very easy:

    if ((browser == 'IE') && (ieVersion <= 10)) 
        // do something, for example:
        document.documentElement.className += ' ie10-';