Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get scroll position and direction with vanilla JS

I'm trying to complete a project without using jQuery. Looking good until now. But, there is something I can't manage: scroll position and direction.

What I basically want is to add a class to an element when we reach a point when going down and remove that class when we reach the same point, but, going up.

like image 678
Axiol Avatar asked Apr 21 '14 20:04

Axiol


1 Answers

You are going to want to use

var scrollObject = {};
window.onscroll = getScrollPosition;

function getScrollPosition(){
    scrollObject = {
       x: window.pageXOffset,
       y: window.pageYOffset
    }
    // If you want to check distance
    if(scrollObject.y > 200) {
        // add class
    } else {
        // remove class
    }
}

That said, I would highly recommend looking into a throttling method to improve performance of this method.

like image 64
Ken Wheeler Avatar answered Oct 24 '22 03:10

Ken Wheeler