The code snippet below will let you get the scroll direction of the document using JavaScript. This is very useful if we want to execute code conditionally based on the document scroll direction (up or down).

	var lastScrollPosition = 0;
	window.onscroll = function() {
		var newScrollPosition = window.scrollY;

		if (newScrollPosition < lastScrollPosition){
			//upward - code here
			//downward - code here
		lastScrollPosition = newScrollPosition;

The code above is attached in the window.onscroll event. We store the initial scroll value into the lastScrollPosition variable. On window scroll, we get the new scroll value and store it into the newScrollPosition variable.

We make a conditional statement that if newScrollPosition is less than lastScrollPosition, the direction is upward, or else the direction is downward.

We then store the the newScrollPosition value into the lastScrollPosition variable to update the last scroll position.