Yahoo! Developer Network Home - Help

YUI Library Examples: YAHOO Global Object: User Agent Detection

YAHOO Global Object: User Agent Detection

This example demonstrates the use of YAHOO.env.ua to identify the user's browser and to branch JavaScript logic based on what browser is being used. (Note: We strongly recommend using feature detection rather than user-agent sniffing to fork code; only use this technique where it is absolutely necessary to do so — for example, in cases where browsers do not report their own capabilities accurately.)


NO IFRAME
Drag over the select

IFRAME
Drag over the select

First, a word of caution

Please DO NOT use this in place of feature detection. Though many browsers have known JavaScript implementation quirks, it is bad practic and unsafe coding to make the assumption that because the page is being viewed in browser X that you can rely on feature Y being available. Check for feature Y if you need it.

Browser sniffing is an imprecise science, and relies on many things in the browser environment to be just right. Though many techniques are very accurate, 100% accuracy can't be guaranteed.

Use the YAHOO.env.ua object to inform you of what browser your page is being viewed in, but for your own sake, do not infer anything from this.

What YAHOO.env.ua looks like

YAHOO.env.ua is an object literal containing keys for most major user agents. The key corresponding to the current browser is assigned a version number. All others have value 0.

There's more information on the YAHOO.env.ua object and value ranges in the API Documentation.

Bundled with the YAHOO Global Object

YAHOO.env comes bundled with the YAHOO Global Object and is used to keep track of what is known about the YUI library and the browsing environment.

If you are using any other YUI component on your page, you should already have YAHOO.env available. Otherwise, add the following:

The example: drag elements and rendering bugs

In this example, we'll add an iframe shim to a Drag and Drop element to account for a known display bug in Internet Explorer 6 regarding the z-indexing of select elements. For you folks out there not using IE6, here's a screen shot of the bug in action.

IE6 shows the select above all elements despite z-indexing

In this case, there is no way other than browser sniffing or conditional comments to address IE's rendering bug. We'll choose sniffing over using proprietary extensions.

Here's the markup for the example:

Targeting a browser for certain action

Here, we create two Drag and Drop elements, then add the shim to the dd2 element if the page is being viewed in a vulnerable version of IE. Normally, of course, you'd add the shim behavior to both, but this will allow us to compare results.

Copyright © 2008 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings