Cross-Browser Layers
Dateline: 07/11/99
The trouble with making high-quality cross-browser Dynamic HTML is that
Netscape and Microsoft have very different implementations of layers.
According to the W3C standards recommendation, the correct way to implement
layers is by using <DIV> and <SPAN> tags (do not use the Navigator
<LAYER> tag). This is all right, because Internet Explorer 4.0+ and
Navigator 4.06+ support all the <DIV> and <SPAN> functionality we
need. The only trouble is that they do it so differently.
Internet Explorer allows you to access any layer (really, any object that as
an ID tag) using document.all. Take the following example
code:
<html>
<head><title>Hello</title></head>
<body>
<div id="Layer1">
This is in Layer 1
<div id="Layer2">
This is in Layer 2
</div>
</div>
</body>
</html>
To access the properties of Layer1 in Internet Explorer, you would use:
document.all.Layer1.property
To access the properties of Layer2, you would use:
document.all.Layer2.property
Pretty straightforward, and it makes plenty of sense to do it this way.
However, if you want to access these layers in Netscape Navigator, you'll have
to use statements like this:
document.layers.Layer1.property
or
document.layers.Layer1.layers.Layer2.property
This is also pretty straightforward, and makes just as much sense as the
Internet Explorer way of doing things. However, the two ways of accessing
layers are fundamentally different. In Internet Explorer, all layers in
the document are accessible under document.all. In Navigator,
the layers form a hierarchy. This means that Layer1 is
accessible under document.layers, but Layer2 is
not. Layer2 is only accessible under document.layers.Layer1.layers.
What I mean is that
document.layers.Layer2
is not defined, because it is a child of document.layers.Layer1
in Navigator.
Writing code that works under either one of these models is a cinch, but
writing code that works under both of these models simultaneously can quickly
become a huge undertaking.
A pretty good solution to this problem is to find the layers on-the-fly using
a custom function (which I'll show you in a minute). For example, you
could say:
theLayer = findLayer("Layer2");
theLayer.property = property;
Where the findLayer function would find the layer called
"Layer2" using document.all if we're in Internet
Explorer, and recursively if we're in Navigator.
Now, here is the code for the findLayer function:
function findLayer(layerName, currLayer)
{
if (document.all && document.all.layerName)
return document.all.layerName;
var layerFound = "";
if (currLayer[layerName] != null)
return currLayer[layerName];
else
{
if (currLayer.layers && currLayer.layers.length > 0)
{
for (i = 0; i<currLayer.layers.length; i++)
{
layerFound = findLayer(layerName, currLayer.layers[i]);
if (layerFound) return layerFound;
}
}
}
return layerFound;
}
More information:
SiteExperts.com:
Cross-Browser DHTML
Visit the message boards!
Previous Features
|