Mathi
Mathi

Reputation: 171

Can someone explain this JS function to me?

I have found this pretty usefull function that tells you if the user scrolls up or down in his browser in pure javascript. I kind of get the first part where the functions triggers every time you scroll and where you ask if the number of pixels is bigger from the previous position than the new one (so a true or false answer expected).

What i don't get : why the function need a parameter (e) and the last part of the function where it says give the value of the old scroll the new scroll value ?

Thank you if you take time to read me, cheers :*

window.onscroll = function isBottom(e) {
  // print "false" if direction is down and "true" if up
  console.log(this.oldScroll > this.scrollY);
  this.oldScroll = this.scrollY;
}

Upvotes: 2

Views: 82

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075079

What i don't get : why the function need a parameter (e)...

It doesn't, you could remove that without changing anything, since nothing in the function's code uses e. Event handlers in even semi-modern browsers are called with an event object as the first argument, but you're not required to declare a parameter (e, in your case) for that argument.

...and the last part of the function where it says give the value of the old scroll the new scroll value ?

That's to remember the last value it saw, so that the next time the scroll event fires, it knows what the value was last time and can tell you what direction the new scroll event is in.

Upvotes: 6

Related Questions