Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the 'relative' position of an element to its parent element? Or: How to find Mr. Blue?

I have basically 2 div elements. The first is a scrolling container and the second one is an element that is placed in the container. I would like to find the y-position relative to the scrolling container. I wrapped all of it into a piece of example-code titled How to find Mr. Blue?

<div style="height:100px; border:solid 1px black; overflow-y:scroll;">
    Please scroll down...
    <br/>
    <div style="height:400px;">
    </div>
    <br/>
    <div id="MrBlue" style="height:20px; background-color:blue; color:white">
        Mr. Blue
    </div>
</div>

So I would like a JavaScript / jQuery statement that alerts the vertical-position of the Mr. Blue. div relative to the scrolling container.

Ps. If you would like to 'fiddle' with mr. Blue, check http://jsfiddle.net/KeesCBakker/Qjr5q/.

like image 217
Kees C. Bakker Avatar asked Mar 16 '11 10:03

Kees C. Bakker


People also ask

How do you find the position of an element relative to a parent?

To get the offset position of an HTML element relative to its parent, you can use the offsetLeft and offsetTop properties of the element. Here is example: const div = document. querySelector('.

How do you find the position of an element?

The correct approach is to use element. getBoundingClientRect() : var rect = element. getBoundingClientRect(); console.

How do you find the position of an element relative to a window?

We can use the getBoundingClientRect method to get an element's position relative to its viewport. We get the div with querySelector . Then we call getBoundingClientRect on it to get an object with the top and left properties. top has the position relative to the top of the viewport.

How to find position of element in jQuery?

jQuery position() Method The 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.


1 Answers

If you can add css position: relative to the wrapping/scrolling container then it's as simple as

document.getElementById('MrBlue').offsetTop

and jsfiddle example http://jsfiddle.net/eU3pN/2/

like image 83
Tom Tu Avatar answered Oct 26 '22 10:10

Tom Tu