Sniffing for Browsers

The key to writing solid DHTML is to find out which browser is looking at your page. To do this, we must do some browser sniffing. If you need to know specific versions of a browser, you can use properties of the navigator object:

navigator.appName
and
navigator.appVersion

This gives you the name of the browser, as well as the version. The example below writes the appName and appVersion to the page. Look at this example in both browsers to see what is returned.



When accessing CSS elements (often referred to as "layers"), it is more efficient to test for support of syntax rather than appName or appVersion. In other words, an IE4+ browser's path to a CSS element begins with "document.all" while a NN4.x browser's path to a CSS element begins with "document.layers". So to find out which browser is looking at your page, you might say:

if (document.all) {
JavaScript statements here
}


Any statement in that if statement's body will only execute if the browser supports the document.all syntax.

Since we will need the path for each browser for every dhtml function we write, its easiest to store the paths in variables. Using syntax support, we'll assign variables representing each browser a boolean (true or false) value. Assigning boolean values to re-usable variables makes your code easy to read.

So, below is the syntax supported by the most widely used browsers as the beginning of the path to the CSS element:
document.all (IE),
document.layers (Netscape 4.x)
document.getElementById (Netscape 6+, IE 5+ and all standards compliant browsers).
Assign our browser-representing variables:

var ie, nn4, dom

if(document.all){
ie = true
else{
ie = false
}

else if(document.layers){
nn4 = true
else{
nn4 = false
}

else if(document.getElementById){
dom = true
else{
dom = false
}
Then to test which browser is viewing the page:
if(nn4){
netscape 4 statements here...
}
else if(ie){
ie statments here...
}
etc.
Rather than using lengthy if/else statements, we can use a special operator in a short hand version of the code above. Enter the conditional operator (?:). The conditional operator is the only JavaScript operator that takes three operands. If the operand to the left of ? evaluates to true, the expression to the left of the : is assigned to the variable, otherwise the expression to the right of the : is assigned.
var nn4 = (document.layers) ? true : false
var ie = (document.all) ? true : false
var dom = (document.getElementById && !document.all) ? true : false
IE 5.5+ browsers support both document.all and document.getElementById. Because of this, we'll need to confine the dom variable to exclude ie browsers to keep statements from returning errors.




Home | Contact