Retrieve the position (X,Y) of an element using HTML
The position of (X, Y) means the coordinate of an element at the top-left point in a document. X represents the horizontal position and Y represents the vertical position. Use element.getBoundingClientRect() property to get the position of an element.
Button Position Retrieval on Webpage
To obtain the position of buttons on a web page, we can use the getBoundingClientRect() method. This method provides us with information about an element’s size and position in the viewport. By using this method, we can obtain the X and Y coordinates of a button when it is clicked.
Example 1: This example shows how to get the position of an element by clicking on the button in an HTML document
html
<!DOCTYPE html>
< html >
< head >
< title >
Retrieve the position (X,Y) of an element
</ title >
< script type = "text/javascript" >
function getPositionXY(element) {
let rect = element.getBoundingClientRect();
document.getElementById('gfg').innerHTML =
'X: ' + rect.x + ', ' + 'Y: ' + rect.y
}
</ script >
</ head >
< body >
< h2 >Retrieve the position (X,Y) of an element using HTML</ h2 >
< 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:
Text Position Retrieval on Webpage
To find where a particular text is on a webpage, we can use the getBoundingClientRect() method. This method tells us about the size of the text and where it is located on the screen when the mouse hovers over it, providing both X and Y coordinates.
Example 2: This example shows by moving the pointer over the document to get the position of an element.
html
<!DOCTYPE html>
< html >
< head >
< title >
Retrieve the position (X,Y) of an element
</ title >
< script type = "text/javascript" >
function getPositionXY(element) {
let rect = element.getBoundingClientRect();
document.getElementById('text').innerHTML
= 'X: ' + rect.x + '< br >' + 'Y: ' + rect.y;
}
</ script >
</ head >
< body >
< h3 >Retrieve the position (X,Y) of an element using HTML</ h3 >
< p >Move the mouse over the text</ p >
< div onmouseover = "getPositionXY(this)" >
Position:
< p id = 'text' ></ p >
</ div >
</ body >
</ html >
|
Output:
Last Updated :
30 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...