'How to get the relative position of an object inside a scrollable div?

enter image description here

I have a scrollable div, the one on the left in the above image.
In this div there exist many elements, lets focus on one of them (highlighted in grey) and call it A.

The right image is a representation of the div with the full size (without scroll or width setting) where A is placed without scrolling.

How may I find the value of X (in green), while having the left div currently on the page.
i.e. taking into consideration:

  1. The div on page is already resized
  2. The div on page is scrollable (and has been scrolled)
  3. I want x not y !

i.e. How to get the relative y coordinate of an element inside a scrollable div ? in simple words: how to calculate x via javascript ?



Solution 1:[1]

Try this :

var elementTop = document.getElementById('yourElementId').offsetTop;
var divTop = document.getElementById('yourDivId').offsetTop;
var elementRelativeTop = elementTop - divTop;

Solution 2:[2]

The approved answer doesn't work if the scrollable div is scrolled. Because it only gets the position of the child element relative to the visible top of the scrollable parent. But if the parent is scrolled, the actual top is no longer the visible top.

This works in all cases:

var topPos = $(elem).offset().top + $(elem).parent().scrollTop() - $(elem).offsetParent().offset().top;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mehbub Rashid