Skip navigation

Access CSS with One Function Call

by Ryan Frishberg
We can edit our script to make all our calls to different browsers much shorter with a generic function to access a layer's CSS properties:

<script language="javascript" type="text/javascript">
      function accessCSS(layerID){      //access a CSS property
            if(document.getElementById){
                  return document.getElementById(layerID).style;
            }else if(document.all){
                  return document.all[layerID].style;
            }else if(document.layers){
                  return document.layers[layerID];
            }
      }
</script>

To access a layer's CSS properties, we can write: accessCSS("myLayer1"). An example would be: accessCSS("myLayer1").top and accessCSS("myLayer1").zIndex.

Shortened Script

Let's apply this newly created generic function to our script we created last section.

<script language="javascript" type="text/javascript">
      function moveLayerLR(layerID,how){      //move layer Left or Right
            accessCSS(layerID).left = parseInt(accessCSS(layerID).left) + how;
      }

      function moveLayerUD(layerID,how){      //move layer Left or Right
            accessCSS(layerID).top = parseInt(accessCSS(layerID).top) + how;
      }
</script>

As you can see, this allows for a much more compact and easily understandable script, and it works exactly the same.

Now, let's make a layer disappear and reappear. And as with most magic tricks, it helps to look behind the screen, except with this one, we won't use "abracadabra."

Next -->