Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 568
Ashraf Bashir Avatar asked Jan 28 '13 13:01

Ashraf Bashir


People also ask

How do you get the scroll position element?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.

What method allows you to get the vertical position of the scroll bar for an element?

The scrollTop() method sets or returns the vertical scrollbar position for the selected elements.

What is scrollTop value?

An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .


1 Answers

Try this :

var elementTop = document.getElementById('yourElementId').offsetTop; var divTop = document.getElementById('yourDivId').offsetTop; var elementRelativeTop = elementTop - divTop; 
like image 96
RodolpheChe Avatar answered Sep 20 '22 16:09

RodolpheChe