Sven
Sven

Reputation: 13295

Do something for every n pixel the window is scrolled

I want to do something for every 27px the window is scrolled. I've written the following code, placed inside a scroll event handler:

scrollSpy++
if (scrollSpy > 27) {
    scrollSpy = 0;
    console.log("27px scrolled");
}

But somehow it's not working.
When I scroll really slow, the events are triggered quite regularly (although I can't tell if it's really after 27px), but when I scroll fast, the event seems to be triggered random/not at all.

I guess the error lies in the assumption that the scroll event is triggered for every px scrolled, because that would be a requirement for the scrollSpy++ method to work.

But of course, I am not sure if that's really the error. How do I do this correctly?

Note: This question is no duplicate of this question, because there the accepted answer is geared towards reel.


Edit:
So based on the answers, I've written this if statement:

if (window.pageYOffset % 27 === 0) {
    // do something
}

But its still not working. When I scroll fast the function fails. So it has something to do with how the scroll event is triggered. Do you know any solution for this? setTimeout or setInterval maybe?

Upvotes: 1

Views: 1046

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

You are correct in your assumption. You should check how much

document.documentElement.scrollTop + document.body.scrollTop

changes between calls of the function. If it increases, the user is scrolling down, and vice versa.

Use this knowledge to determine when to do whatever you're doing.

Upvotes: 2

Ry-
Ry-

Reputation: 224942

No, scroll events aren’t triggered for every pixel scrolled. Anyways, you can just use window.pageYOffset instead, with fallbacks as necessary as described in the MDN documentation for pageYOffset, and check in which direction and by how much that value changes on each scroll event.

Upvotes: 1

Related Questions