0

I would like to know how to implement java script that allows me to add a css class to an element when i scroll and to remove it when i stop scrolling. on/off situation

  • Your question is a little bit too general. What would be the primary goal of your implementation? Fastest or easiest to implement? Best performance? Portability? Though honestly, all of the above would be solved by jQuery, as long as you're not developing for mobile. – Tony Chiboucas Jun 06 '16 at 20:07
  • Have you tried searching for libraries such as [ScrollMagic](http://scrollmagic.io)? – gcampbell Jun 06 '16 at 20:09
  • Possible duplicate of [jQuery scroll() detect when user stops scrolling](http://stackoverflow.com/questions/9144560/jquery-scroll-detect-when-user-stops-scrolling) – showdev Jun 06 '16 at 20:19

1 Answers1

0

Try it like this:

$(window).on('scroll', function() {
  $('#someID').addClass('red');
});

$(window).scroll(function() {
  clearTimeout($.data(this, 'scrollTimer'));
  $.data(this, 'scrollTimer', setTimeout(function() {
    $('#someID').removeClass('red');
  }, 250));
});

Class .red just adds red color for testing.

You can test it here https://jsfiddle.net/byxpsnwu/

I used this SO answer.

Community
  • 1
  • 1
Jakob
  • 3,493
  • 4
  • 26
  • 42