<as*******@hotmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
Hi,
I am using the following code to show/hide part of an html page. It
works in Netscape and Firefox but dies in IE: "Error: document.layers
is null or not an object"
<style>
.noshow {
display: none;
}
.menu {
display: block;
}
</style>
<script language="javascript>
if (document.getElementById)
{
function getElemById(id)
{
return document.getElementById(id);
}
}
else if (document.all)
{
function getElemById(id)
{
return document.all(id);
}
}
else if (document.layers)
{
function getElemById(id)
{
return document.layers[id];
}
}
function hide(ele)
{
getElemById(ele).className = "noshow";
}
function show(ele)
{
getElemById(ele).className = "menu";
}
</script>
Then in the html part:
<a href="javascript:show('category');">Show Categories</a>
<div id="category" class="noshow">
...
...
<a href="javascript:hide('category');">Hide Categories</a>
</div>
Lots of people have explained why you are seeing what you are seeing,
but I don't think anyone has given you a clear way to resolve it:
<script type="text/javascript">
var d = document;
var gEBI;
if (d.getElementById) {
gEBI = function(id) { return d.getElementById(id); }
} else if (d.all) {
gEBI = function(id) { return d.all(id); }
} else {
gEBI = function() { return { style:{} }; }
}
function hide(id) { gEBI(id).className = "noshow"; }
function show(id) { gEBI(id).className = "menu"; }
}
Because you use -gEDI- without testing what it returns a generic version
of -gEBI- that returns a new Object is required so that you can assign
a -className- property to it without causing an error.
Since assigning -className- to the object returned by
document.layers[id] doesn't do anything either, I removed that test and
have only two tests for document.getElementById and document.all.
Netscape 4 will use the generic function that returns a "fake" node.
The reason I have the generic version of the function return {
style:{} } is so you can do things like:
gEBI(id).style.display = 'none';
and it won't cause an error in Netscape 4 (it won't do anything either,
but presumably you have graceful degradation for Netscape 4 anyway).
--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ -
http://jibbering.com/faq