The position of (X, Y) means the co-ordinate of an element at the top-left point in a document. X represent the horizontal position and Y represent the vertical position. Use element.getBoundingClientRect() property to get the position of an element.
Example 1:
<!DOCTYPE html>
< html >
< head >
< title >
position of an element
</ title >
< script type = "text/javascript" >
function getPositionXY(element) {
var rect = element.getBoundingClientRect();
document.getElementById('gfg').innerHTML =
'X: ' + rect.x + ', ' + 'Y: ' + rect.y
}
</ script >
</ head >
< body >
< button id = 'button1' onclick = "getPositionXY(this)" >
Button 1
</ button >
< button id = 'button1' onclick = "getPositionXY(this)" >
Button 2
</ button >
< br >< br >
< button id = 'button1' onclick = "getPositionXY(this)" >
Button 3
</ button >
< p id = 'gfg' ></ p >
</ body >
</ html >
|
Output:

Example 2: In this example, move the pointer over the document to get the position of an element.
<!DOCTYPE html>
< html >
< head >
< title >
position of an element
</ title >
< script type = "text/javascript" >
function getPositionXY(element) {
var rect = element.getBoundingClientRect();
document.getElementById('text').innerHTML
= 'X: ' + rect.x + '< br >' + 'Y: ' + rect.y;
}
</ script >
</ head >
< body >
< p >Move the mouse over the text</ p >
< div onmouseover = "getPositionXY(this)" >
Position:
< p id = 'text' ></ p >
</ div >
</ body >
</ html >
|
Output:
