Correct way to get Scroll Position

Viewed 603
2 Answers

recently i had the same problem. So in order to get the position as a percentage I end up do the following

window.addEventListener("scroll", function() {

    const maxHeight = document.body.scrollHeight - window.innerHeight;
    console.log((window.pageYOffset * 100) / maxHeight);
});

We subtract window.innerHeight from document.body.scrollHeight besause window.pageYOffset represents the top of the viewport. So in order for window.pageYOffset to match document.body.scrollHeight we do the above subtraction.

PS.: The above returns a float number. you can use parseInt(...) to convert it to integer if you'd like.

Related