scrollUpMenu.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. (function (win) {
  2. window.scrollUpMenu = (function () {
  3. var element;
  4. var klass;
  5. var handler;
  6. var minScroll = 300; // Arbitrary limit before the hider kicks in.
  7. var doc = win.document;
  8. var previousPos = win.pageYOffset;
  9. function init(elSelector, cls) {
  10. // Pass in element and class name.
  11. // Only run for slightly more capable browsers – short-circuit if
  12. // some properties are not available:
  13. // (See http://responsivenews.co.uk/post/18948466399/cutting-the-mustard)
  14. if(!(
  15. elSelector
  16. && cls
  17. && 'querySelector' in doc
  18. && 'addEventListener' in win
  19. && 'classList' in doc.createElement('_'))) {
  20. return;
  21. }
  22. element = doc.querySelector(elSelector);
  23. klass = cls;
  24. win.addEventListener('scroll', handler);
  25. win.addEventListener('hashchange', handler);
  26. }
  27. // Helper to "debounce" a function call, meaning it has to wait
  28. // at least a certain amount of time before being called again
  29. // so that the function is not run too often.
  30. // See https://remysharp.com/2010/07/21/throttling-function-calls
  31. function debounce(fn, delay) {
  32. var timer = null;
  33. return function () {
  34. var context = this, args = arguments;
  35. clearTimeout(timer);
  36. timer = setTimeout(function () {
  37. fn.apply(context, args);
  38. }, delay);
  39. };
  40. }
  41. function toggleMenu() {
  42. var top = win.pageYOffset;
  43. if ((top > minScroll) && top > previousPos) {
  44. element.classList.add(klass);
  45. }
  46. else {
  47. element.classList.remove(klass);
  48. }
  49. previousPos = top;
  50. }
  51. handler = debounce(toggleMenu, 200);
  52. // Public-facing API.
  53. return {
  54. init: init,
  55. };
  56. }());
  57. }(window));