I need to detect not only the browser type but version as well using jQuery. Mostly I need to find out if it is IE 8 or not.
I am not sure if I am doing it correctly
You can use $.browser to detect the browser name. possible values are :
or get a boolean flag: $.browser.msie will be true if the browser is MSIE.
as for the version number, if you are only interested in the major release number - you can use parseInt($.browser.version, 10). no need to parse the $.browser.version string yourself.
Anyway, The $.support property is available for detection of support for particular features rather than relying on $.browser.
Don't forget that you can also use HTML to detect IE8.
<!--[if IE 8]>
<script type="text/javascript">
ie = 8;
</script>
<![endif]-->
Having that before all your scripts will let you just check the "ie" variable or whatever.
This should work for all IE8 minor versions
if ($.browser.msie && parseInt($.browser.version, 10) === 8) {
alert('IE8');
} else {
alert('Non IE8');
}
-- update
Please note that $.browser is removed from jQuery 1.9
I think the best way would be this:
From HTML5 boilerplate:
<!--[if lt IE 7]> <html lang="en-us" class="no-js ie6 oldie"> <![endif]-->
<!--[if IE 7]> <html lang="en-us" class="no-js ie7 oldie"> <![endif]-->
<!--[if IE 8]> <html lang="en-us" class="no-js ie8 oldie"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en-us" class="no-js"> <!--<![endif]-->
in JS:
if( $("html").hasClass("ie8") ) { /* do your things */ };
especially since $.browser has been removed from jQuery 1.9+.
You can easily detect which type and version of the browser, using this jquery
$(document).ready(function()
{
if ( $.browser.msie ){
if($.browser.version == '6.0')
{ $('html').addClass('ie6');
}
else if($.browser.version == '7.0')
{ $('html').addClass('ie7');
}
else if($.browser.version == '8.0')
{ $('html').addClass('ie8');
}
else if($.browser.version == '9.0')
{ $('html').addClass('ie9');
}
}
else if ( $.browser.webkit )
{ $('html').addClass('webkit');
}
else if ( $.browser.mozilla )
{ $('html').addClass('mozilla');
}
else if ( $.browser.opera )
{ $('html').addClass('opera');
}
});
If you fiddle with browser versions it leads to no good very often. You don't want to implement it by yourself. But you can Modernizr made by Paul Irish and other smart folks. It will detect what the browser actually can do and put apropriate classes in <html>
element. However with Modernizr, you can test IE version like this:
$('html.lt-ie9').each() {
// this will execute if browser is IE 8 or less
}
Similary, you can use .lt-ie8
, and .lt-ie7
.