Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate distance between li element and viewport using JavaScript

As shown in figure below...

Black box is the screen size, the viewport. The red dotted box is the size of the entire page, which has been scrolled out of the viewport. The green dotted boxes are li elements. Now I want to calculate the distance between a specific li and the top edge of the viewport, represented by the red arrow.

I'm okay with a jQuery solution.

screen and viewport scratch

like image 585
Hong Liu Avatar asked Oct 20 '25 09:10

Hong Liu


2 Answers

var distanceToTop = document.querySelector("#your-li").getBoundingClientRect().top
like image 171
Rūdolfs Vikmanis Avatar answered Oct 21 '25 21:10

Rūdolfs Vikmanis


Quite easy with jQuery too :

Demo

$('#element').offset().top-$(window).scrollTop();

Best of both worlds :

$('#element')[0].getBoundingClientRect().top;
like image 26
Shikkediel Avatar answered Oct 21 '25 23:10

Shikkediel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!