Contact Me


Recent Posts


Categories


Archives


Tags

3d actionscript Actionscript 2 Actionscript 3 api APIs as2 as3 brand carousel channel code compress contest contract CSS Flash flv fp10 free gadget gadgets gdata google JavaScript jquery mvc papervision papervision3d PHP player playlist proxy puremvc pv3d Python search tube tutorial twitter video widget XML you youtube

Links


Help end world hunger

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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:

1
2
3
4
5
6
7
8
9
10
11
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.


8 Responses to “Quick jQuery Browser Detection Snippet”

Leave a Reply

Your comment:

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Fork me on GitHub