jQuery position: Main Tips
- jQuery
.position()
delivers the position of the first matched element relative to the offset parent. - The .offset() method differs form
position()
in that it makes jQuery get position of element relative to the document.
Usage of .position() Method
The jQuery .position()
returns the coordinates of the element position relative to the offset parent. In the example below, this information is shown in an alert that appears upon clicking a button:
$("button").click(() => {
var coordinate = $("div").position();
alert("Top: " + coordinate.top + " Left: " + coordinate.left);
});
As you make jQuery get element position, these properties of an element are returned:
top
: vertical position relatively to the top side of its parent element.left
: horizontal position relatively to the left side of its parent element.
The syntax for the .position()
jQuery method takes no arguments:
$(selector).position();
Remember: jQuery does not deliver position information of hidden elements.