[Contents] [Prev page] [Next page] [Last page]

Using JavaScript To Access Layers

You can use JavaScript to dynamically create and modify layers.

The Layer Object

For each layer in an HTML page there is a corresponding JavaScript layer object. A layer object has properties that are a reflection of the layer's properties. Some layer properties can be directly modified by assignment; for example, "mylayer.visibility = hide". A layer object also has methods that can affect these properties.

As with all JavaScript objects, a layer object's properties and methods can be accessed in the following ways:

Here, layerName refers to the layer object, propertyName is one of the following properties, and methodName is one of the following methods.

The Layer Object Properties

Table 2.1 Layer Object Properties

Property Name

Modifiable by user?

Description

name

N

The name assigned to the layer through the NAME attribute in the <LAYER> tag.

left

Y

The horizontal position of the layer's left edget, in pixels, relative to the origin of its parent layer.

top

Y

The vertical position of the layer's top edge, in pixels, relative to the origin of its parent layer.

pageX

Y

The horizontal position of the layer, in pixels, relative to the page.

pageY

Y

The vertical position of the layer, in pixels, relative to the page.

zIndex

Y

The relative z-order of this layer with respect to siblings and parent. Sibling layers with lower numbered z-index's are stacked underneath this layer. A layer with a negative zIndex value is always stacked below its parent layer and a layer with a non-negative zIndex always appears above its parent layer.

Note: In pre-release 4, negative values are not allowed for zIndex.

visibility

Y

Determines whether or not the the layer is visible. A value of show means show the layer; hide means hide the layer; inherit means inherit the visiblity of the parent layer.

clip.top

clip.left

clip.right

clip.bottom clip.width clip.height

Y

These properties define the clipping rectangle, which specifies the part of the layer that is visible. Any part of a layer that is outside the clipping rectangle is not displayed.

background

Y

The image to use as the background for the layer's canvas (which is the part of the layer within the clip rectangle).

Each layer has a background property, whose value is an image object, whose src attribute is a URL that indicates the image to use to provide a tiled backdrop The value is null if the layer has no backdrop.

For example:

layer.background.src = "fishbg.gif";
bgColor

Y

The color to use as a solid background color for the layer's canvas (which is the part of the layer within the clip rectangle). The value can be an encoded RGB value, a string that indicates a pre-defined color, or null for a transparent layer

For example:

//blue background
layer.bgColor = "0000FF"; 
// red background
layer.bgColor = "red";
// transparent layer
layer.bgColor = null;
siblingAbove

N

The layer object above this one in z-order, among all layers that share the same parent layer or null if the layer has no sibling above.

siblingBelow

N

The layer object below this one in z-order, among all layers that share the same parent layer or null if layer is bottomost.

above

N

The layer object above this one in z-order, among all layers in the document or the enclosing window object if this layer is topmost.

below

N

The layer object below this one in z-order, among all layers in the document or null if this layer is bottomost.

parentLayer

N

The layer object that contains this layer, or the enclosing window object if this layer is not nested in another layer.

src

Y

Source of the content for the layer, specified as a URL.

The Layer Object Methods

Table 2.2 Layer Object Methods

Method Name

Description

moveBy(x, y)

Changes the layer position by applying the specified deltas, measured in pixels.

moveTo(x, y)

Changes the layer position to the specified pixel coordinates within the containing layer. For ILayers, moves the layer relative to the natural inflow position of the layer.

moveToAbsolute(x, y)

Changes the layer position to the specified pixel coordinates within the page (instead of the containing layer.)

resizeBy(width, height)

Resizes the layer by the specified height and width values (in pixels). Note that this does not relayout any HTML contained in the layer. Instead, the layer contents may be clipped by the new boundaries of the layer.

This method has the same effect as setting the clip.width and clip.height.

resizeTo(width, height)

Resizes the layer to have the specified height and width values (in pixels). Note that this does not relayout any HTML contained in the layer. Instead, the layer contents may be clipped by the new boundaries of the layer.

moveAbove(layer)

Stacks this layer above the layer specified in the argument, without changing either layer's horizontal or vertical position. After re-stacking, both layers will share the same parent layer.

moveBelow(layer)

Stacks this layer below the specified layer, without changing the layer's horizontal or vertical position. After re-stacking, both layers will share the same parent layer.

load(sourcestring, width)

Changes the source of a layer to the contents of the file indicated by sourcestring, and simultaneously changes the width at which the layer's HTML contents will be wrapped.

This method takes two arguments. The first argument is a string indicating the external file name, and the second is the width of the layer as a pixel value.

The Document Property of Layers and the Layers Property of Documents

Each document has a layers property that contains an array of all the top-level layers in the document. Each layer in turn has a document property. This document property has a layers array that contains all the top-level layers inside this layer. The document of a layer also has all the usual properties of a documen object, such as the images property, that contains an array of all the images in the layer, as well as properties that contain arrays for all the applets, embeds, links, and named anchors in that layer.

For example, consider the following HTML text:

<HTML>
<BODY>
<LAYER NAME = "LAYER1">
  <P>Layer 1 content. </P>
</LAYER>
<LAYER NAME = "LAYER2">
  <P>Layer 2 content. </P>
    <LAYER NAME = "LAYER2.1">
    <P>Layer 2.1 content. </P>
    </LAYER>
</LAYER>
</BODY>
</HTML>

The following statements illustrate the use of of the document and layers properties.

// value is an array of two layers:
document.layers 
// value is layer1:
document.layers["layer1"] 
// value is layer2:
document.layers["layer2"] 
// Invalid. Gives an error. 
// layer2.1 is not at the top level:
document.layers["layer2.1"] 
// value is layer2.1:
document.layers["layer2"].document.layers["layer2.1"]

Using Javascript, you can access an object in a layers array by its index (a non-negative integer) or by using the name specified by its NAME attribute in the <LAYER> or <ILAYER> tag.

When accessed by integer index, array elements appear in z-order from back to front, where zero is the bottommost layer and higher layers are indexed by consecutive integers. The index of a layer is not the same as its zIndex property, as the latter does not necessarily enumerate layers with consecutive integers. Also, adjacent layers can have the same zIndex property values, but tow layers can never occupy the same index in the array.

These are valid ways of accessing layer objects:

  document.layers[index] 
  document.layers["layerName"] 
  // example of using layers property to access nested layers:
   document.layers["layer2"].document.layers["layer2.1"]

Elements of a layers array are JavaScript objects that cannot be set by assignment, though their properties can be set. For example, the statement

       document.layers[0]="music"

is invalid (and ignored) because it attempts to alter the layers array. However, the properties of the objects in the array are readable and some are writable. For example, the statement

       document.layers["suspect1"].left = 100;

is valid. This sets the layers horizontal position to 100. The following example sets the background color to blue for the layer bluehouse which is nested in the layer houses.

  
document.layers["houses"].document.layers["bluehouse"].bgColor="blue";

You can find the number of layers in a in a layers array by obtaining its length property:

  document.layers.length
  document.layers["houses"].document.layers.length

Creating Layers Dynamically

You can create new Layer objects by calling the new operator on a Layer object, for example:

bluelayer = document.layers["bluelayer"]
newbluelayer = new Layer(300, bluelayer)

The first argument is the width of the new layer, and the second argument, which is optional, is its parent layer. If you do not supply a parent layer, the new layer will be a top-level layer.

After creating a new layer, you can set its source either by setting a value for its SRC property, or by calling the load method. Alternatively, you can open the layer's document and write to it (as discussed in the next section.)

There are a few important things to know about creating layers and modifying their contents dynamically. You can only create a new Layer object by using the new operator after the page has completely finished loading. You cannot open a layer's document and write to it until the page has finished loading. You can only have one layer open for writing at a time.

Writing to Layers

While initially defining a layer, you can write to the layer's document using the document's write method. (This is a somewhat complicated way of defining the content of a layer, however.)

<LAYER NAME="layer1" BGcolor="green">  
  <HR>
  <H1>First Heading</H1> 
  <SCRIPT>
    document.write("<P>Here is some content<P>")
  </SCRIPT>
  <HR>
</LAYER>

In this case, the contents of the layer will be:

After a layer has been initially created and the page has fully finished loading, you can modify the contents of the layer by using the write() method of the layer's document. If you use the write method to write content to a layer after the layer has been created, the original content of the layer is wiped out, and replaced by the new content.

After writing to a layer's document, you need to close the document.

For example:

<LAYER NAME="layer1" BGCOLOR="blue">  
  <HR>
  <H1>First Heading</H1> 
  <P>Here is the original content<P>
  <HR>
</LAYER>
</BODY>
</HTML>
<SCRIPT>
function changeLayerContent() {
  document.layers["layer1"].document.write("<HR><P>New content.</P><HR>");
  document.layers["layer1"].document.close();
}
</SCRIPT>

<FORM NAME="form">
<INPUT TYPE=button VALUE="CHANGE CONTENT" 
ONCLICK='changeContent();return false;'>
</FORM>

Event Handling in Layers

Each layer can be thought of as a separate containing document. It has the same event-handling capabilities as a top level window. You can capture events for a layer. The <LAYER> tag also takes the following event handlers:

onMouseOver 
onMouseOut 
onLoad 
onFocus 
onBlur 

The onMouseOver event handler is invoked when the mouse cursor moves into a layer.

The onMouseOut event handler is invoked when the mouse cursor moves out of the area of a layer.

The onLoad event handler gets invoked when a layer is loaded, that is, the document that ultimately contains the layer is displayed. This is true regardless of whether a layer is visible or not.

The onFocus handler is invoked when the layer gets keyboard focus, and the onBlur handler is invoked when the layer loses keyboard focus.

Just as in the case of a document, if you want to define mouse click response for a layer, you must capture onMouseDown and onMouseUp events at the level of the layer and process them as you want.

See the JavaScript Reference for more details of capturing events.

If an event occurs in a point where mutliple layers overlap, the top-most layer gets the event, even if it is transparent. However, if a layer is hidden, it does not get events.

Scripts in Layers

You can use the <SCRIPT> and </SCRIPT> tags in a layers. The functions defined in the script will be scoped to the layer that contains them, and they cannot be used outside the layer.

This functionality is handy, for example, for defining event handlers for a layer.

<LAYER NAME="layer1" BGCOLOR="red"
    onMouseOver='changeColor("blue")'
    onMouseOut='changeColor("red")'>
  <P>Layer content...</P>
  <SCRIPT>
    function changeColor(newcol) {
     bgColor=newcol;
     }
  </SCRIPT>
</LAYER>

Whent the mouse moves into the layer, the layer turns blue. When the mouse moves out of the layer, it turns red.

Animating Layers

You can use the setTimeout JavaScript function to animate layers. This function basically calls another function after a given amount of time. Thus a function can call setTimeout on itself so that it is continuously invoked.

The setTimeOut() function has two different forms:

setTimeOut("code to be executed", delay)
setTimeOut(fn, delay, args...)

For example, to invoke doItAgain("Sam", "piano") after 3 milliseconds, you can use either of the following statements:

setTimeout("doItAgain('Sam', 'piano')", 3)
setTimeout("doItAgain, 3, "Sam", "piano");

The following continuously makes a layer 5 pixels wider and 5 pixels higher until the layer is 450 pixels wide.

function expand(layer) 
{
    if (layer.clip.right < 450) {
    layer.resizeBy(5, 5);
    setTimeout("expand", 5, layer);
    }
  return false;
}

Animating Images

Many interesting animations can be achieved by changing the source of an image in conjunction with moving the image. To move an image, you can change the position of the layer that contains the image. To change the source of the image, you can assign a new value to the SRC property of the image.

If the source of the image is changed too quickly or too often, the actual image may not download across the net quickly enough to keep up with the animation. Therefore if you have a script that changes the source of an image in a moving layer, it is best to make sure that the image has fully loaded before you try to do anything with it.

One way to prefetch an image is to display it in a layer. When a layer loads, it loads all its content, including all images, regardless of whether the layer is visible or not. If a page has a hidden layer that contains all the images needed in the animation then when the page opens, the source for the images will be downloaded into the browser's cache, even though they will not be visible.

The Examples section contains an example, Changing the Stacking Order of Fish and Pole Layers that, illustrates the use of a hidden layer to contain images that are not needed when the page opens but are used in the course of animating the contents of the page.



[Contents] [Prev page] [Next page] [Last page]

Copyright © 1997, Netscape Communications. All rights reserved.