Dynamically retrieve the position (X,Y) of an HTML element
Dynamically retrieve the position (X,Y) of an HTML element
by Nirvanachain
HTML
<div class="container">
<div class="box"> </div>
<div id="hotspot"> </div>
</div>
<p id="printHere"> </p>
CSS
.container {
position:relative;
}
.box {
width:300px;
height:100px;
background-color:#88b7d5;
}
#hotspot {
position:absolute;
left:20px;
top:50px;
width:20px;
height:20px;
border-radius:10px;
background-color:#d55357;
}
JavaScript
var printHere = document.getElementById('printHere');
var hotspot = document.getElementById('hotspot');
var rect = hotspot.getBoundingClientRect();
printHere.innerHTML += 'Top = ' + rect.left + '<br />';
printHere.innerHTML += 'Left = ' + rect.left + '<br />';
printHere.innerHTML += 'Bottom = ' + rect.bottom + '<br />';
printHere.innerHTML += 'Right = ' + rect.right;