ElemPosCalc

by Hyunsok Oh

HTML

<button id="btn1" onclick="myFunction()">Open "myWin"</button>
<button id="btn2" onclick="checkPosition()">Check "myWin" positio</button>
<button id="btn3" onclick="checkBtnPosition()">Check button position</button>
<button id="btn4" onclick="alertWinPos()">check window position</button>

JavaScript

var myWindow;

function myFunction() {
  myWindow = window.open("", "myWin", "left=50, top=50");
  //myWindow.document.write("<p>This is 'myWin'<button id='btn1'>This is button on window</button>");
  //myWindow.document.write("<br>ScreenLeft: " + myWindow.screenLeft);
  //myWindow.document.write("<br>ScreenTop: " + myWindow.screenTop + "</p>");
}

function checkPosition() {
  //myWindow.document.write("<p>This is 'myWin'");
  //myWindow.document.write("<br>ScreenLeft: " + myWindow.screenLeft);
  //myWindow.document.write("<br>ScreenTop: " + myWindow.screenTop + "</p>");
}

function GetScreenCoordinates(obj) {
  var p = {};
  p.x = obj.offsetLeft;
  p.y = obj.offsetTop;
  p.toString = function() {
    return "(" + this.x + "," + this.y + ")"
  }
  while (obj.offsetParent) {
    p.x = p.x + obj.offsetParent.offsetLeft;
    p.y = p.y + obj.offsetParent.offsetTop;
    if (obj == document.getElementsByTagName("body")[0]) {
      break;
    } else {
      obj = obj.offsetParent;
    }
  }

  // add window screen offset
  p.x = p.x + window.screenLeft
  p.y = p.y + window.screenTop
  return p;
}

function checkBtnPosition() {
  var btn1 = document.getElementById("btn1")
  var btn2 = document.getElementById("btn2")
  var btn3 = document.getElementById("btn3")
  var p1 = GetScreenCoordinates(btn1)
  var p2 = GetScreenCoordinates(btn2)
  var p3 = GetScreenCoordinates(btn3)
  if (myWindow) {
    var btn4 = myWindow.document.getElementById("btn1")
    var p4 = GetScreenCoordinates(btn4)
    alert("p1=" + p1 + ",p2=" + p2 + ",p3=" + p3 + ",win=" + p4)
  } else {
    alert("p1=" + p1 + ",p2=" + p2 + ",p3=" + p3)
  }
}

function alertWinPos() {
  alert("l=" + window.screenLeft + "t=" + window.screenTop);
}