Advertisement
Guest User

Untitled

a guest
Oct 9th, 2015
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. var currentScrollPosY = 0,
  2. scrollPosY = 1,
  3. busy = false,
  4. onTop = true,
  5. myElement = document.getElementById("MyElement");
  6.  
  7. function onScroll() {
  8. // get current scroll position from window
  9. currentScrollPosY = window.scrollY;
  10.  
  11. // ensure that events don't stack
  12. if (!busy) {
  13. // if we were above, and are now below scroll position...
  14. if (onTop && currentScrollPosY > scrollPosY) {
  15. // suspend accepting scroll events
  16. busy = true;
  17.  
  18. // remember that we are below scroll position
  19. onTop = false;
  20.  
  21. // asynchronuously add style / class to element
  22. requestAnimationFrame(belowScrollPos);
  23. // if we were below, and are now above scroll position...
  24. } else if (!onTop && currentScrollPosY <= scrollPosY) {
  25. // suspend accepting scroll events
  26. busy = true;
  27.  
  28. // remember that we are above scroll position
  29. onTop = true;
  30.  
  31. // asynchronuously add style / class to element
  32. requestAnimationFrame(aboveScrollPos);
  33. }
  34. }
  35. };
  36.  
  37. function aboveScrollPos() {
  38. // add style / class to element
  39. myElement.classList.add("aboveScrollPos");
  40. myElement.classList.remove("belowScrollPos");
  41.  
  42. // resume accepting scroll events
  43. busy = false;
  44. };
  45.  
  46. function belowScrollPos() {
  47. // add style / class to element
  48. myElement.classList.add("belowScrollPos");
  49. myElement.classList.remove("aboveScrollPos");
  50.  
  51. // resume accepting scroll events
  52. busy = false;
  53. };
  54.  
  55. // register for window scroll events
  56. window.addEventListener('scroll', onScroll, false);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement