My Technical Notes

Tuesday, 9 December 2014

IEVersionizr.js - a method of adding IE specific classes


(function () {
    function getIEVersion() {
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf('MSIE ');
        var trident = ua.indexOf('Trident/');

        if (msie > 0) {
            // IE 10 or older => return version number
            return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
        } else if (trident > 0) {
            // IE 11 (or newer) => return version number
            var rv = ua.indexOf('rv:');
            return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
        } else {
            return NaN;
        }
    };

    var cssClasses = [];

    var ieVersion = getIEVersion();
 
    cssClasses.push(isNaN(ieVersion) ? 'no-ie' : 'ie');;

    if (!isNaN(ieVersion)) { // if it is IE
            var minVersion =  Math.min(ieVersion, 6); 
            var maxVersion = Math.max(ieVersion, 11);

            cssClasses.push('ie' + ieVersion + ' lte-ie' + ieVersion + ' gte-ie' + ieVersion);

            if (minVersion < ieVersion) {
                for (var i = minVersion; i < ieVersion; ++i) {
                    cssClasses.push('gt-ie' + i + ' gte-ie' + i);
                }
            }
  
            if (ieVersion < maxVersion) {
                for (var i = ieVersion + 1; i <= maxVersion; ++i) {
                    cssClasses.push('lt-ie' + i + ' lte-ie' + i);
                }
            }
        }
 
        // set the html element 'class' attribute
        document.getElementsByTagName('html').item(0).className += ' ' + cssClasses.join(' ');
 
        window.IEVersionizr = {
            ie : !isNaN(ieVersion),
            ieversion : ieVersion
        };
    })();

No comments: