Get the Position of an Element with JavaScript

Web Design & Web Development

In this article, I will introduce how to get the position of an element with JavaScript.

The position relative to the window

To get the position relative to the window of an element (clientX/clientY), use the method getBoundingClientRect().
The value obtained by this method depends on the page scroll.

The code is as below.

let targetElement = document.getElementById('target');

let clientX = targetElement.getBoundingClientRect().left;
let clientY = targetElement.getBoundingClientRect().top;
Sponsored links

The position relative to the document

To get the position relative to the document (pageX/pageY), add the current page scroll (scrollX/scrollY) to clientX/clientY.

The code is as below.

let targetElement = document.getElementById('target');

let clientX = targetElement.getBoundingClientRect().left;
let clientY = targetElement.getBoundingClientRect().top;

let scrollX = window.pageXOffset;
let scrollY = window.pageYOffset;

let pageX = clientX + scrollX;
let pageY = clientY + scrollY;
Sponsored links

Demo

Sponsored links

Code

HTML

<div id="target">Target</div>

<p class="position">
  clientX = <span id="cX"></span><br>
  clientY = <span id="cY"></span><br>
  scrollX = <span id="sX"></span><br>
  scrollY = <span id="sY"></span><br>
  pageX = <span id="pX"></span><br>
  pageY = <span id="pY"></span>
</p>

JavaScript

function getPosition() {
  let targetElement = document.getElementById('target');

  let cX = document.getElementById('cX');
  let cY = document.getElementById('cY');

  let sX = document.getElementById('sX');
  let sY = document.getElementById('sY');

  let pX = document.getElementById('pX');
  let pY = document.getElementById('pY');

  let clientX = targetElement.getBoundingClientRect().left;
  let clientY = targetElement.getBoundingClientRect().top;

  let scrollX = window.pageXOffset;
  let scrollY = window.pageYOffset;

  cX.innerHTML = clientX;
  cY.innerHTML = clientY;

  sX.innerHTML = scrollX;
  sY.innerHTML = scrollY;

  pX.innerHTML = clientX + scrollX;
  pY.innerHTML = clientY + scrollY;
}

function updatePosition() {
  getPosition();
}

window.addEventListener('scroll', updatePosition, false);
window.addEventListener('resize', updatePosition, false);