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

1

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.

    
asked by anonymous 25.03.2017 / 02:27

1 answer

3

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)
}

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>
    
25.03.2017 / 08:50