Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the top left x and y coordinate using javascript

I know that we can get width and height using clientWidth and clientHeight, however how do I figure out the top left x and top left y position of an element?

like image 222
xonegirlz Avatar asked Dec 03 '22 00:12

xonegirlz


1 Answers

function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

Retrieve the position (X,Y) of an HTML element

Find X/Y of an HTML element with JavaScript

These two links should be helpful.

like image 71
Sameera Thilakasiri Avatar answered Dec 15 '22 00:12

Sameera Thilakasiri