Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting `distance` of scroll

usinf javascript is it possible to work out the distance, or how far in pixels a window has been scrolled down?

Regards Phil

like image 619
Phil Jackson Avatar asked Dec 13 '09 14:12

Phil Jackson


People also ask

How do I get scroll distance?

To make this work, we need to detect scroll events using addEventListener() . var scrollDistance = function (callback) { // Make sure a valid callback was provided if (! callback || typeof callback !== 'function') return; // Variables var isScrolling, start, end, distance; // Listen for scroll events window.

How do you find the distance from the top of the viewport?

top, distance = (elementOffset - scrollTop); The distance variable now holds the distance from the top of the #my-element element and the top-fold. Note that negative values mean that the element is above the top-fold. Save this answer.

How get scroll count in jquery?

$(document). ready(function(){ var scrollPos = 0; var Counter = 0; $(window). scroll(function(){ var scrollPosCur = $(this). scrollTop(); if (scrollPosCur > scrollPos) { Counter -= 1; } else { Counter += 1; } scrollPos = scrollPosCur; }); });

What is scroll offset?

forward, then scroll offset is the amount the top of the sliver has been scrolled past the top of the viewport. This value is typically used to compute whether this sliver should still protrude into the viewport via SliverGeometry.


2 Answers

This will work to get the distance of an element from the top of the document: document.documentElement.scrollTop

You need to make sure that the element is scrollable.

From Mozilla MDN:

If the element can't be scrolled (e.g. it has no overflow or if the element is non-scrollable), scrollTop is set to 0

like image 183
Alex Avatar answered Sep 26 '22 13:09

Alex


Catch all browsers including IE

var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop

From http://www.javascriptkit.com/javatutors/detect-user-scroll-amount.shtml

like image 34
Will Avatar answered Sep 23 '22 13:09

Will