Positioning Layers in JavaScript
Quite often it is necessary to position layers
dynamically using JavaScript. Possible reasons for that could
be to place a layer at a constant screen position so that
it is visible independent of the current scroll position or
to follow the mouse pointer.
The CSS Solution
If you would like to place a layer at a constant screen position
independent of the current scroll position, there is a very
simple solution to this: use Cascading Style Sheets (CSS).
Cascading Style Sheets allow you to specify the screen position
of a layer using the attributes
position, top, left, width, height and z-index.
The attribute
position:fixed;
should do exactly what we want, namely to keep the position
of the layer you are using this style attribute on constant.
However, this does not work in all browsers. This time the
black sheep is the Internet Explorer. Netscape 7, Mozilla
1.1 and Opera 7 work fine.
Click here
for a simple example to see if your browser works fine.
Workaround using JavaScript
As the Internet Explorer does not support the CSS attribute
"position:fixed" properly, we should not use it
at all in order to get the same result in all browsers. A
possible solution for this is to use JavaScript. There are
other solutions as well, but as far as I can tell, a JavaScript
is the easiest way.
What we need to do:
- Define a layer. We then set the layers positioning style
to "relative" using CSS.
- Determine the current scroll position by catching each
scroll event.
- Place the layer at a position with constant distance relative
to the current scroll position.
Actions to take:
Define the layer you want to place dynamically. Let's call
it "mov_image". Use CSS to define the initial position
and positioning style plus the z-index. The most easiest way
is to use relative positioning (this means relative to the
parent container, e. g. a table's cell).
<div id="mov_image" style="position:relative;
top:0px; left:0px; z-index:1;"><!-- put your contents
here --></div>
Add the following code in the "head" section of
your HTML page.
|