How to get position of an element relative to the document or parent using jQuery ?
In order to get the location of an element relative to the document, jQuery offset() method is used. The offset() method is an inbuilt method in jQuery which is used to set or returns the offset coordinates of the selected element. We can also use the jQuery position() method. The position() method is an inbuilt method in jQuery which is used to find the position of the first matched element relative to its parent element in the DOM tree.
Syntax:
$(selector).offset()
Below examples illustrate the above approach:
Example 1:
<!DOCTYPE html>
< html >
< head >
< title >
How to get the Location of
an element relative to the
document using jQuery?
</ title >
< style >
h1 {
color: green;
}
body {
text-align: center;
}
</ style >
< script src =
</ script >
</ head >
< body >
< h1 >GeeksforGeeks</ h1 >
< b >
How to get the Location of an
element relative< br > to the
document using jQuery/JavaScript?
</ b >
< br >< br >
< div id = "Logo" >
< img src =
</ div >
< br >< br >
< button type = "button" >Click</ button >
< h4 ></ h4 >
< script >
$(document).ready(function() {
$("button").click(function() {
var offset = $("#Logo").offset();
$("h4").text("Location of the box is: (left: " +
offset.left + ", top: " + offset.top + ")");
});
});
</ script >
</ body >
</ html >
|
Output:
Example 2:
<!DOCTYPE html>
< html >
< head >
< title >
How to get the Location of
an element relative to the
document using jQuery?
</ title >
< style >
h1 {
color: green;
}
body {
text-align: center;
}
</ style >
< script src =
</ script >
</ head >
< body >
< h1 >GeeksforGeeks</ h1 >
< b >
How to get the Location of an
element relative< br > to the
document using jQuery/JavaScript?
</ b >
< br >< br >
< div id = "Logo" >
< img src =
</ div >
< br >< br >
< button type = "button" >Click</ button >
< h4 ></ h4 >
< script >
$(document).ready(function() {
$("button").click(function(){
var position = $("#Logo").position();
$("h4").text("Location of the Logo is: (left: "
+ position.left + ", top: " + position.top + ")");
});
});
</ script >
</ body >
</ html >
|
Output:
Last Updated :
18 Mar, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...