Ahmed Nuaman


builder of internets ~ developer of dreams ~ tamer of Dachshunds

Quick jQuery Browser Detection Snippet

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:

function detectBrowsers()
{
    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:

function ready()
{
    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.

Where have comments gone?

Good question my old fruity. I'm now sticking any post discussions on Google+. Why? Well simply it's better. WordPress's comment system isn't very elegant and nor are ones like Disqus or Livefyre, so to save hassle I've just shipped them off to a social network, like a real boss.

Search

My social skills

Latest blog posts

  • Loading posts...

Subscribe in a reader

Latest tweets

  • Loading tweets...