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.
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.
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)
}
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>
-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;
}
Try to contextualize your answer
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.
Thank you, Sergio!
– Seu Madruga