Skip to content
Learn to use jQuery position method with demo
In This Tutorial
The $.position method of jQuery
The jQuery position method is used to return position or coordinates of the given element. The coordinates are relative to the parent element of given element and values are in pixels.
See an example of position method
In order to return or set the coordinates relative to document use the offset method of jQuery.
The $.position method will get the coordinates of the first matched element if there are multiple occurrences of the matched element.
Syntax of position() method
The basic syntax to get coordinates:
$(“element”).position();
Following is an example of using the position jQuery method.
Getting coordinates example
In the following example, we have used a div element along with a span element. As you click the button, the alert will show the coordinates of the span element.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
<html>
<head>
<script src=“http://code.jquery.com/jquery-1.10.1.min.js”></script>
<script>
$(document).ready(function(){
$(“button”).click(function(){
var position = $(“span”).position();
alert(“Top: “ + position.top + “n” + ” Left: “ + position.left);
});
});
</script>
<style>
div
{
padding: 15px;
border: solid 1px;
}
span
{
margin-left: 10px;
border: solid 1px;
}
</style>
</head>
<body>
<div id=“offsetdiv”>This is div element <br />
<span>This is span, child of div</span>
</div>
<button id=“offset”>Click to see coordinates of span</button>
</body>
</html>
|
Further reading: jQuery offset
Leave A Comment?