Constructing an API
Now that we have browser-representing variables, the next step in simplifying dhtml tasks includes incorporating those variables into all our other dhtml functions. To achieve this, start by using the browser variables in a function which takes an argument that represents the id of the layer we need to access with JavaScript.
This variable we'll call, "path" returns both the varying browser paths to the layer and the id name of the layer which is defined when the function is called. The correct path to any layer we send the browser function, or any other function that calls the browser function is now at our beck and call.
Placing the below function within a JavaScript source file is the first step in writing an API - application programming interface. Along with the browser sniffing function, you can place as many "grunt work" functions in the same file for repeated use.
var nn4 = (document.layers) ? true : false
var ie = (document.all) ? true : false
var dom = (document.getElementById && !document.all) ? true : false
function browser(id){
if(nn4) {
path = document.layers[id]
}
else if(ie) {
path = document.all[id]
}
else {
path = document.getElementById(id)
}
return path //return the path to the css layer depending on which browser is looking at the page
}
For example, say we have a layer whose id name is "bob".
<div id="bob"> content here </div<
We want to hide bob and his contents on the fly when clicking a link that invokes a simple function. In that function, we first need the path to bob. That is easily accomplished now that we have the browser sniffing function on hand:
function hideLayer(id){
var layer = browser(id) // call browser sniffing function, assign variable name to returned value
if(nn4){
layer.visibility = "hidden"
}
else {
layer.style.visibility = "hidden"
}
}
To change the layer's visibility property, just call the hideLayer() function:
<a href="javascript:hideLayer('bob')">hide bob</a>
NOTE: many of Netscape 6 and Internet Explorer's CSS properties are contained within the style object. But some are not. Since most property names are different from NN4 to IE to NN6 (the visibility property is an exception), and some branching is already neccessary in almost every function, these examples simply add the style object to the path when needed.