Last update on August 19 2022 21:51:35 [UTC/GMT +8 hours]
jQuery Practical exercise Part - I : Exercise-26
Find the absolute position of an element using jQuery.
Sample Solution:
HTML Code :
Find the absolute position of an element using jQuery
First name:
Last name:
JavaScript Code:
var left_position = $["
# name2"].offset[].left - $[document].scrollTop[];
console.log['Left: '+left_position];
var top_position = $["
# name2"].offset[].top - $[document].scrollTop[];
console.log['Right: '+top_position];
See the Pen jquery-practical-exercise-26 by w3resource [@w3resource] on CodePen.
Contribute your code and comments through Disqus.
Previous: Access form input fields using jQuery. Next: Convert a jQuery object into a string.
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:
`
`2
`3
`2
`5
`2
`7
`9
0
> `
`4
`9`head`5
> `
`1
2
> 1
> `
`
`1
2
> 1
> `
`
`
`4> `
`2
`27
`
`9
`
`9`html
>
Output:
`
`2
`3
`2
`64
`2
`7
`9
0
> `
`4
`9`head`5
> `
`1
2
> 1
> `
`
`1
2
> 1
> `
`
`
`4> `
`2
`27