Positioning Elements


el.style.left = "0px"; el.style.posLeft = 0; el.style.top = "0px"; el.style.posTop = 0; 

CSS supports two ways to position an element: absolute positioning and relative positioning. No matter which method you choose, with JavaScript you can set the positioning values. Usually, the absolute positioning is more convenient since you do not have to calculate relative positions of nested elements then.

In most browsers, the left property defines the x coordinate of the element, and the top property is used for the y coordinate. The values are not numeric butas usual in CSSinclude a unit, usually px for pixels.

For Internet Explorer, you need a different approach. The posLeft and posTop properties set the horizontal and vertical position; however, this time, you just provide a numeric value, no unit.

The most convenient approach is to just set all of these properties, since there are no side effects. This saves you from client sniffing.

The following code positions the <div> element in the upper-left corner. Note that this element now lies over the text on the page.

Positioning an Element (position.html)

<script language="JavaScript"   type="text/javascript"> function position() {   var el = document.getElementById("element");   el.style.left = "0px";   el.style.posLeft = 0;   el.style.top = "0px";   el.style.posTop = 0; } window.onload = position; </script> <h1>My Portal</h1> <p>Some sample text. Some sample text.   Some sample text. Some sample text.   Some sample text. Some sample text.   Some sample text. Some sample text.   Some sample text. Some sample text.   Some sample text. Some sample text. </p> <div  style="position: absolute; background-color: #eee; border: 1px solid"> JavaScript Phrasebook </div> 




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net