How to take the position X and Y of an element, relative to the screen?

Asked

Viewed 10,552 times

1

I would like, when an element is clicked, to get its coordinates on the page.

The issue isn’t even the onclick event, but how do I get these coordinates?

No libs/frameworks, please.

2 answers

3


You can use the .getBoundingClientRect() thus:

function posicao(e) {
    var el = this;
    var coordenadas = el.getBoundingClientRect();
    console.log('posição x', coordenadas.left, 'posição y', coordenadas.top)
}

Example:

function posicao(e) {
    var el = this;
    var coordenadas = el.getBoundingClientRect();
    var res = 
    console.log('posição x', coordenadas.left, 'posição y', coordenadas.top)
}

document.getElementById('meio').addEventListener('click', posicao);
document.getElementById('fundo').addEventListener('click', posicao);
#meio, #fundo {
    background: #ccd;
    padding: 30px;
    position: absolute;
    border: 2px solid #500;
    cursor: pointer;
}

#meio {
    top: 50%;
    left: 50%;
}

#fundo {
    bottom: 0;
    right: 0;
}
<div id="meio"></div>
<div id="fundo"></div>

  • 1

    Thank you, Sergio!

-2

html

<div onmousemove="showCoords(event)" onmouseout="clearCoor()" onclick="getCoor(event)"></div>

js

function showCoords(event) {
  var x = event.clientX;
  var y = event.clientY;
  var coor = "X coords: " + x + ", Y coords: " + y;
  document.getElementById("demo").innerHTML = coor;
}

function getCoor(event) {  
  var x = event.clientX;
  var y = event.clientY;
  var coor = "X coords: " + x + ", Y coords: " + y;
  document.getElementById("demo2").innerHTML = coor;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.