Positioning DIV Layers

Question: How do I re-position a DIV layer on my page using JavaScript?

Answer: To re-position a DIV layer myLayerID, in Internet Explorer you need to set myLayerID.style.posLeft and myLayerID.style.posTop to the integer coordinates of the desired position of the layer's top left corner. In most other browsers, the style properties posLeft and posTop are not supported. Instead, in non-IE browsers you would need to set myLayerID.style.left and myLayerID.style.top to the desired coordinates in the format Xpx and Ypx, respectively. Note that here you must specify the units (px) after the coordinate values.

Here's an example that works in most modern browsers by combining both of the above techniques:

This example uses the function setPostion. Below is the JavaScript source code of this function:

function setPosition (id,leftX,topY) {
 var layerRef = document.getElementById(id);

 if (layerRef==null) return;

 if (null!=layerRef.style.left) {
   layerRef.style.left = leftX+'px';
   layerRef.style.top  = topY+'px';
 if (null!=layerRef.style.posLeft) {
   layerRef.style.posLeft = leftX;
   layerRef.style.posTop  = topY;
See also:
  • How do I create a new positioned DIV layer from JavaScript?
  • How do I delete a layer using JavaScript?
  • Copyright © 1999-2011, JavaScripter.net.