★ wanayoo — archive 1999 http://developer.netscape.com/viewsource/angus_layers/angus_layers.htmlNouvelle recherche | Portail wanayoo



View Source Front Page JavaScript / DHTML Java Language Netscape Servers Open Standards and Architectures E-Commerce Human Interface Case Studies Third-Party News

SCRIPTING LAYER EFFECTS AND TRANSITIONS

JavaScript Building Blocks for Layer Manipulation

by ANGUS DAVIS


Editor's Note: We're providing this article to give you an early look at the Netscape Communicator layers feature and JavaScript 1.2 in response to developer demand for information about these important subjects. As of this writing, the feature set for Communicator is still subject to minor change. All the techniques Angus describes are supported in the latest preview release, unless otherwise noted, and you can put them to immediate use. To the best of our knowledge, all the techniques will be supported in the final customer release. Should support for any of the methods used here change, we'll be sure to alert you.


Send comments and questions about this article to View Source.

With the release of Netscape Communicator comes Navigator 4, which supports a powerful new set of elements called layers. This article focuses on controlling layers through JavaScript. It assumes that you've already read the Communicator layers online documentation, which offers an introduction to the new HTML tags and related JavaScript. The documentation takes only a few minutes to skim; doing so will help you understand this article. Also, to see the examples described here, you need to use Netscape Communicator; you can download the latest release from the Netscape Home page.

By building on the existing JavaScript functions that give us control over a layer's size, appearance, and position, we can build a more complex set of methods that allow us to make effects such as "sliding" page elements into place or "closing curtains" on part of a Web page that can be viewed by Navigator 4.0. We'll look at some of those methods here; we'll also examine ways of determining more information about the Navigator drawing "environment," such as window size and position. Once you're armed with these basic tools, you'll be able to create more complicated applications using layers. This article is designed to give you code snippets and explanations to act as building blocks in your own layer-enabled applications.


LAYERS FOR LAYMEN

For those of you venturing into the world of layers without having read the documentation, I'll provide a brief introduction to layers.

In order to understand why we have layers, we need to look back at some of the historic problems with HTML. Since its inception, HTML has been a great tool for easily publishing information to the masses. Unfortunately, however, HTML didn't support the absolute control over layout and positioning offered by traditional desktop publishing tools. Such precision allows publishers to align and overlay images, text, and other items in more powerful page layout programs.

Layers give HTML the power it needs to precisely control the position of any element or group of elements - including text, images, applets, embedded objects, and forms - within a Web document. In addition to defining the x and y coordinates (called left and top in layer lingo) of such an element, layers allow you to control their visibility, in essence allowing you to make any particular layer visible or invisible at will. Finally, layers allow you to control these elements' Z-order, that is, the order in which they overlap one another.

Layers are represented in Web documents by the <layer> tag and its attributes; they can be programatically controlled by new JavaScript 1.2 methods and properties. For a complete introduction to the tag, its attributes, and corresponding JavaScript, consult the layers documentation.


SLIP, SLIDING AWAY . . . .

Let's start looking at how layers can be manipulated. Imagine being able to move an image in a layer across the screen a few pixels at a time, to give the illusion that the image is sliding across the screen. JavaScript gives us the moveTo() function, but doesn't offer any means of slowly sliding an element from one coordinate to another. To do this, we'd need to specify starting and ending coordinates, the number of steps to take, and the time between these steps to control the speed of the slide. Let's examine a new function that we'll define, called slideLayer(), shown in Example 1.


Example 1

<script language="JavaScript">
function slideLayer(lyr,xinc,yinc,inctime,xstop) {
 lyr.top += yinc
 lyr.left += xinc
 if (((xinc > 0) && (lyr.left < xstop)) ||
     ((xinc < 0) && (lyr.left > xstop))) {

setTimeout('slideLayer(document.layers["'+lyr.name+'"],'+xinc+',
           '+yinc+','+inctime+','+xstop+')',inctime)
     } 
}
</script>

NOTE: In the above code, the line beginning with "setTimeout" is wrapped here for readability purposes. That statement must appear on one line in your final code to work properly.



This function uses five variables. First, lyr defines the layer in the document we want to slide. If we had a layer called "myLayer," we could pass document.layers ['myLayer'] as a valid value for lyr. Second, xinc and yinc specify how much the left and top values of the layer should be moved each increment. Steps are timed by inctime, which specifies the delay time between increments in milliseconds. Finally, xstop designates a certain x value at which the slide will be completed.

To slide a layer to the left, we'd use negative xinc values; for moving layers down, positive yinc values. Positive xinc values move the layer to the right, while negative yinc values move a layer up. The table "Layer Movement" illustrates this more clearly.

LAYER
MOVEMENT
xinc < 0 xinc > 0
yinc < 0 Layer moves up and to the left Layer moves up and to the right
yinc > 0 Layer moves down and to the left Layer moves down and to the right

To see how this function works in a Web page, let's try sliding a page title graphic (contained in a layer) into place. To see this in action, view a sample page that demonstrates our slideLayer() function, then read over the example source code for that document.

If you're adventurous, you may want to try improving this function by allowing changes in increment size over the course of the slide to produce a curving motion effect. For instance, if you slightly increase or decrease the size of the increment as the process takes place, you could make the layer appear to move along curves instead of diagonal lines. For those of you who aren't so geometrically inclined, the script snippet in Example 1 should be all you need to start "slip, sliding away" with layers in Navigator 4.


DROPPING THE CURTAIN

In addition to moving a layer around the window, there are other visual effects that warrant further investigation. We can create transitions with layers to give viewers the illusion of a curtain closing on a Web page. We can accomplish this feat by again making small changes over time to the layer's attributes - in this case, the clipping width and height.

We'd like to create functions for sliding a layer's horizontal and vertical clipping width that are easy to implement. The JavaScript function shown in Example 2 allows us to slide a layer open or closed horizontally; it uses variables similar to those we just explored in the slideLayer() function in Example 1. As you'll see, we can use this function to generate the desired curtain effect.


Example 2

<SCRIPT language="JavaScript">
function curtainWide(lyr,xinc,inctime,stopwidth) {
lyr.clip.left += -(xinc/2)
lyr.clip.right += (xinc/2)
if (lyr.clip.width < 0) {lyr.clip.width = 0}
if (((xinc < 0) && (lyr.clip.width > stopwidth)) ||
    ((xinc > 0) && (lyr.clip.width < stopwidth))) {
     setTimeout('curtainWide(document.layers["'+lyr.name+'"],'+xinc+',
                '+inctime+','+stopwidth+')',inctime)
    }
}
</SCRIPT>

NOTE: In the above code, the line beginning with "setTimeout" is wrapped here for readability purposes. That statement must appear on one line in your final code to work properly.



The code snippet in Example 2 allows us to "slide" the clipping width of the layer in and out symmetrically, yielding a transition effect similar to that of side-stage curtains sliding closed or open. To help understand how this function works, let's see it in action on our trusty title-bar graphic (contained in a layer, of course). You can see how to reference this method in your page by viewing the source code of our sample page.

The function works by reducing the left and right clipping widths a little bit each increment. The complicated if statement determines when to stop the effect. Sometimes, the curtain closes too far, resulting in annoying negative clipping width values that can sometimes make a layer appear to grow back a pixel or two during this effect. To counter this, we've included a line to catch this possibility, and replace all negative clipping width values with zero. It works together to deliver an eye-pleasing transition.

To build a function to handle vertical versions of what we've created here, we simply replace the width, left, and right references with names denoting height, top, and bottom. When we've finished building this new function, which we'll call curtainHigh(), it should look something like the code snippet shown in Example 3.


Example 3

<SCRIPT language="JavaScript">
function curtainHigh(lyr,yinc,inctime,stopheight) {
lyr.clip.top += -(yinc/2)
lyr.clip.bottom += (yinc/2)
if (lyr.clip.height < 0) {lyr.clip.height = 0}
if (((yinc < 0) && (lyr.clip.height > stopheight)) ||
    ((yinc > 0) && (lyr.clip.height < stopheight))) {
     setTimeout('curtainHigh(document.layers["'+lyr.name+'"],'+yinc+',
                '+inctime+','+stopheight+')',inctime)
    }
}
</SCRIPT>

NOTE: In the above code, the line beginning with "setTimeout" is wrapped here for readability purposes. That statement must appear on one line in your final code to work properly.


Check out Example 3 in action, and then view the source for a more complete look. As you can see, it works just like our curtainWide() function did, yet it modifies the layer's clipping height instead of its clipping width.


ADVANCED CLIPPING TRICKS

Modifying a layer's clipping rectangle is another great trick we can use for making Web-page transitions; it's something we can use in many different fashions to yield eye-pleasing results. One possible application would be to create a spotlight effect, which would seem to cast a moving spotlight across a layer.

By incrementally moving a small clipping rectangle across a layer's intended width, we can give a moving, bite-size glimpse of the layer. As this bite-size glimpse passes over the larger layer beneath, the user is given the illusion that a spotlight is passing over the layer. The function that lies at the heart of this effect is shown in Example 4.


Example 4

<script language="JavaScript">
function spotLight(lyr,litewidth,inctime,lyrwidth,xstep,direction) {
lyr.clip.left += direction*xstep
lyr.clip.right += direction*xstep
if ((lyr.clip.right > lyrwidth) ||
    (lyr.clip.left < 0)) {
      direction *= -1
    }
setTimeout('spotLight(document.layers["'+lyr.name+'"],'+litewidth+',
           '+inctime+','+lyrwidth+','+xstep+','+direction+')',inctime)
}
</script>

NOTE: In the above code, the line beginning with "setTimeout" is wrapped here for readability purposes. That statement must appear on one line in your final code to work properly.


Our example function, called spotLight(), uses quite a few parameters, outlined in the table below ("spotLight() Parameters"). Of particular interest is the lyrwidth parameter, which we use to let our function know the actual width of the layer. (Although we'll eventually be able to use a layer's width property in JavaScript, it hadn't been implemented as of Communicator Preview Release 2. Of course, when this is implemented, we can modify our function so that we won't need to pass this parameter specifically.)

spotLight()
Parameters
lyr The layer we're applying the effect to
litewidth The width, in pixels, of our bite-size glimpse, or spotlight
inctime The time, in milliseconds, between increments, which controls the movement speed of the spotlight
lyrwidth The width of the layer (Note: a layer's width is not exposed to JavaScript in Communicator Preview Release 2, but it will be by the complete customer release)
xstep The size, in pixels, of horizontal spotlight movement during each increment
direction The current direction of the spotlight; positive for right to left, negative for left to right


For a better understanding, see the spotLight() function in action, then view the source of our example page.

Once you're comfortable using this code on your own, you'll be able to modify it to better suit your needs. For instance, you can choose to make the spotlight move vertically, or, for a really complicated project, you might make a spotlight box bounce around a layer's outer bounds in diagonal motions. The possibilities with layers and visual effects using clipping tricks are nearly endless.


WHERE AM I?

Working with layers is exciting, because it gives us more control over the absolute positioning of elements in an HTML document. We can specify x and y coordinates for almost anything using layers. But this brings up an important limitation: How do we know the size and dimensions of the drawing area that's available to us? How can we tell layers where they are in the big picture?

Consider a layer that we'd like to center on the user's document window, the drawing area within the browser window, also called the canvas. On a browser currently sized to be 640-pixels wide, the center location is at pixel 320. However, on a browser sized to be 800-pixels wide, that location is pixel 400. We need a way to both reflect the current dimensions of the browser window as well as methods to change those properties, if needed. We'd also like to know where the window is located within the desktop.

JavaScript in Navigator 4 gives us new properties and methods for just these purposes; they're essential for working with absolute positioning of layers. Some of these properties and methods weren't implemented in time for the Communicator Preview Release 2; examining them now, however, can provide valuable insight into the bigger picture, especially if you're considering making serious use of layers.

In Netscape Navigator 2 and 3, we could control the width and height of a window only by opening a new window and specifying the width and height in a call to window.open(). Navigator 4 gives us the ability to resize the current window, through the window.resizeTo() method, which was implemented in Communicator Preview Release 1. To resize the current window to 640-pixels wide by 480-pixels high, we use the following JavaScript code:

window.resizeTo(640,480)

This is a tremendously powerful tool, which aids in absolute positioning by allowing us to control the size of the document window. But what if we'd rather not resize the current window, preferring instead to simply find out the current window's width and height? To do this, we can turn to the window.width and window.height properties. Although these properties hadn't been implemented in Communicator Preview Release 2, they will eventually provide valuable information about the confines of the document window.

Finally, consider the possiblity of controlling a window's location within the screen on a user's computer - in essence telling the window where it is on the virtual desktop. If you resize a window to the user's maximum screen size, it's possible that the Navigator window will appear at least partially off-screen, unless the window is positioned to the top-most, left-most position. JavaScript in Navigator 4 gives us the window.moveTo() method, which allows us to reposition a window to any x or y coordinate on the user's screen. This method was implemented in Communicator Preview Release 1.

CONCLUSION

As more new JavaScript methods are implemented in subsequent preview releases of Communicator, you'll see additional documentation and specifications on the Netscape DevEdge Web site. The preliminary JavaScript 1.2 specification, which outlines these and other methods and properties in detail, is available to all Netscape ONE licensees. The few methods and properties outlined here give us a small peek at what's possible when we combine absolute positioning and layers with JavaScript.

Without a doubt, layers are one of the most powerful new features of Communicator. With the building blocks described here in hand, you should be on your way to building impressive Web-based applications that use layers-based visual effects. Please write us to explain how you're using layers in your site. If you're really pushing the outside of the envelope and you'd like to tell other developers about how you're doing that, we'd be happy to work with you on an article for a future edition of View Source.


FINDING OUT MORE:
If you're interested in finding out more about layers then DevEdge Online hosts the following items that you may find of use:
Dynamic HTML Documentation
Netscape Communicator pod: This area includes layers syntax, canvas mode syntax and some great layers demos by both Netscape and third party developers.


View Source wants your feedback!
Write to us and let us know
what you think of this article.


Angus Davis is presently on a one-year hiatus from Emory University, working at Intelecom Data Systems as a Web developer. When he's not busy building LiveWire applications or tackling client-side JavaScript on his HAL 9000 computer, you can find Angus in the DevEdge discussion group netscape.devs-client-technical where he acts as a Netscape DevEdge Champion. An aspiring writer, Angus is presently conducting reseach for the never-to-be published book entitled Mozilla: The Unauthorized Biography. An avid skier and sailor, Angus disconnects from the Net occasionally to visit with his family and his girlfriend.

(2.97)

For the latest technical information on Sun-Netscape Alliance products, go to: http://developer.iplanet.com

For more Internet development resources, try Netscape TechSearch.


Copyright © 1999 Netscape Communications Corporation.
This site powered by: Netscape Enterprise Server and Netscape Compass Server.