Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the absolute position of an element using jQuery?

Is there a way of finding the absolute position of an element, i.e. relative to the start of the window, using jQuery?

like image 244
akshat Avatar asked Mar 25 '09 20:03

akshat


People also ask

How do you find the absolute position of an element?

The correct approach is to use element. getBoundingClientRect() to Get absolute position of element in JavaScript. Use element id to get its position in the browser window.

What is offset () in jQuery?

jQuery offset() Method The offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.

How do I set relative position in jQuery?

jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.

How do you get the position of an element in a JavaScript?

Use the Element. getBoundingClientRect() Function to Get the Position of an Element in JavaScript. The getBoundingClientRect() function produces a DOMRect object containing information about an element's size and position in the viewport.


2 Answers

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 } 

You can use this return value to position other elements at the same spot:

$(anotherElement).css(position) 
like image 179
Crescent Fresh Avatar answered Sep 19 '22 05:09

Crescent Fresh


Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

like image 24
Tom Auger Avatar answered Sep 18 '22 05:09

Tom Auger