Page 1 of 1

Getting position and size of html element in javascript

Posted: 20 Apr 2017, 08:13
by MarPlo
Hello,
How can I get the position top, left of a html element in page, for example a Div or an image?
Also, how to get the size of a specified Div: width and height?

Getting position and size of html element in javascript

Posted: 20 Apr 2017, 08:22
by Admin
This function, getBoxPS(), can be used to get the position and size (in pixels) of html elements in page.
It returns an object with four properties: {x:left, y:top, w:width, h:height}

Code: Select all

//JavaScript function to get position and size of html element - https://coursesweb.net/javascript/
//receives the element; returns object: {x:left, y:top, w:width, h:height} in pixels
function getBoxPS(elm){
  function getOffset(object,offset){if(!object)return;offset.x+=object.offsetLeft;offset.y+=object.offsetTop;getOffset(object.offsetParent,offset);}
  function getScrolled(object,scrolled){if(!object)return;scrolled.x+=object.scrollLeft;scrolled.y+=object.scrollTop;if(object.tagName.toLowerCase()!='html')getScrolled(object.parentNode,scrolled);}
  function getZoomFactor(){var factor=1;if(document.body.getBoundingClientRect){var rect=document.body.getBoundingClientRect();var physicalW=rect.right-rect.left;var logicalW=document.body.offsetWidth;factor=Math.round((physicalW/logicalW)*100)/100;}
  return factor;}
  var re={x:0,y:0,w:0,h:0};if(elm.getBoundingClientRect){var rect=elm.getBoundingClientRect();var x=rect.left;var y=rect.top;var w=rect.right-rect.left;var h=rect.bottom-rect.top;if(navigator.appName.toLowerCase()=='microsoft internet explorer'){x-=document.documentElement.clientLeft;y-=document.documentElement.clientTop;var zoomFactor=getZoomFactor();if(zoomFactor!=1){x=Math.round(x/zoomFactor);y=Math.round(y/zoomFactor);w=Math.round(w/zoomFactor);h=Math.round(h/zoomFactor);}}
  re={x:Math.round(x),y:Math.round(y),w:Math.round(w),h:Math.round(h)};}
  else{var offset={x:0,y:0};getOffset(elm,offset);var scrolled={x:0,y:0};getScrolled(elm.parentNode,scrolled);var x=offset.x-scrolled.x;var y=offset.y-scrolled.y;var w=elm.offsetWidth;var h=elm.offsetHeight;re={x:Math.round(x),y:Math.round(y),w:Math.round(w),h:Math.round(h)};}
  return re;
}
- An example with this function is to this page: https://coursesweb.net/javascript/position-size-div-page