46
  1. What's the equivalent of the following in plain JS?

    $(window).scroll(function() { });

  2. I'm also looking to animate scroll, e.g.:

    $('html, body').animate({scrollTop:1750}, 'slow');

Should I be using requestAnimationFrame?

http://paulirish.com/2011/requestanimationframe-for-smart-animating/

Are there any examples that trigger an animation once on click and not continuous renders?

Fish Below the Ice
  • 1,273
  • 13
  • 23
Neo
  • 1,027
  • 3
  • 12
  • 30

1 Answers1

74

Question 1

window.onscroll = function() {
    console.log('scrolling');
};

or if your targeted browsers support addEventListener :

window.addEventListener('scroll', function() {
        console.log('scrolling');
});

Question 2

In my opinion, if you're just scrolling from one section to a another section of your page, and not having some sort of constantly running scrolling movement, you're fine doing this without using requestAnimationFrame.

You can find good implementations of scrolling to a particular part of the window in pure javascript, I suggest checking out their source(or even using them).

freethejazz
  • 2,235
  • 14
  • 19
  • Can you clarify what you mean by "if its supported"? Is this because some browsers (IE) don't support `addEventListener`, or is it that they don't fire the `scroll` event? – Will Brickner May 24 '17 at 08:27
  • @WillBrickner I meant if `addEventListener` is supported. Editing now for clarity. – freethejazz May 26 '17 at 21:22
  • Be careful if you use window.onscroll though. If you have two functions which you append to the window one of them will not work as you overwrite the previous function. This will result in a difficult to debug problem. – Pascal Knecht Nov 19 '19 at 13:28
  • Is it possible to modify this solution so the function will be called on scroll only once? – Olga B Jun 08 '20 at 05:35
  • 1
    @OlgaB You can do this by wrapping the scroll handler in a debounce function. You can find good implementations of them in common JavaScript libraries or implement debouncing yourself (it's a great way to understand closures and higher-order functions). – freethejazz Jul 20 '20 at 11:19
  • @JonathanF I know about a debounce function but never tried it. Thank you very much! Good point. :) – Olga B Jul 21 '20 at 12:04