Thursday, July 16th, 2009
Update: I’ve added a little example below…
As most of you know there lurks browsers that we don’t really like building web sites for (*cough* Internet Explorer) and there comes a time in any developers work when they need to detect browsers. jQuery has a really nice API for detecting browsers, but sometimes you want to go a bit further.
The snippet I’m putting on this page will detect the browser and OS for you and add a nice little CSS class to the body tag, thus allowing you to write up all your CSS ready for users of different browser and OS creed.
Here it is:
{
if ( $.browser.msie )
{
if ( $.browser.version == '8.0' )
{
$('body').addClass( 'ie8' );
}
else if ( $.browser.version == '7.0' )
{
$('body').addClass( 'ie7' );
}
else
{
$('body').addClass( 'ie6' );
}
}
if ( $.browser.safari )
{
if ( navigator.userAgent.indexOf( 'Safari' ) != -1 )
{
$('body').addClass( 'safari' );
}
else
{
$('body').addClass( 'chrome' );
}
}
if ( $.browser.mozilla )
{
if ( $.browser.version.substr( 0, 3 ) == '1.9' )
{
$('body').addClass( 'ff3' );
}
else
{
$('body').addClass( 'ff2' );
}
}
if ( navigator.userAgent.indexOf( 'Windows' ) != -1 )
{
$('body').addClass( 'windows' );
}
else if ( navigator.userAgent.indexOf( 'Mac' ) != -1 )
{
$('body').addClass( 'mac' );
}
}
And how would you use it? Well I’d suggest something like this:
{
detectBrowsers();
}
function detectBrowsers()
{
...
}
$(document).ready( ready );
Now you may be thinking “what about Linux?”. Well our good friends who use Linux tend to use FireFox 2/3, and that’s good, so they’re good, therefore I don’t really need to check for them.
Here’s a little example for you to mull over:
Tell me what you think.