2

How can I find what's the distance between top of the parent div and top of the child div ?

enter image description here

For example how can I know at what distance (height) div 2 starts related to parent div ? so I can scroll to it ?

Tarida George
  • 1,303
  • 3
  • 17
  • 36

3 Answers3

1

You can use jQuery to find div2's position:

$('.div2').offset();

And how much you've already scrolled (if any):

var scrolled = $(window).scrollTop();

Then just subtract them

var distanceFromTop = offset.top - scrolled

This gives you the distance between the top of Div2, and the top of the viewport. Now you can tell your script to scroll down by that amount, or not to scroll if you're already past it.

kthornbloom
  • 3,660
  • 2
  • 31
  • 46
  • I marked @bjb568 answer as 'accepted answer' because I didn't specified that I need javascript or jquery and because his answer contain examples, but your answer is good too. Thanks ! – Tarida George Jan 28 '14 at 20:43
1

You can use div.getBoundingClientRect().top to return the distance from top of the viewport. Just subtract the parent's getBoundingClientRect().top from it. (Fiddle, MDN)

BUT: Since you only need to scroll there, you can use div.scrollIntoView() (answered here, MDN)

Community
  • 1
  • 1
bjb568
  • 11,089
  • 11
  • 50
  • 71
0

Will this help in any way?

function pxToInt(val) {
    return parseInt(val.replace('px', ''));
}

var a = pxToInt($('#parent').attr('padding-top'));
var b = pxToInt($('#div1').attr('margin-top'));
var c = pxToInt($('#div1').innerHeight());
alert(a + b + c);
Ashraf Samhouri
  • 408
  • 3
  • 8