I would like, when an element is clicked, to give it a get in its coordinates on the page.
The issue is neither the onclick event, but how do I get these coordinates?
No libs / frameworks, please.
I would like, when an element is clicked, to give it a get in its coordinates on the page.
The issue is neither the onclick event, but how do I get these coordinates?
No libs / frameworks, please.
You can use .getBoundingClientRect()
like this:
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>