scroll.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Detect request animation frame
  2. var scroll =
  3. window.requestAnimationFrame ||
  4. // IE Fallback
  5. function (callback) {
  6. window.setTimeout(callback, 1000 / 60);
  7. };
  8. var elementsToShow = document.querySelectorAll(".show-on-scroll");
  9. function loop() {
  10. Array.prototype.forEach.call(elementsToShow, function (element) {
  11. if (isElementInViewport(element)) {
  12. element.classList.add("is-visible");
  13. } else {
  14. element.classList.remove("is-visible");
  15. }
  16. });
  17. scroll(loop);
  18. }
  19. // Call the loop for the first time
  20. loop();
  21. function isElementInViewport(el) {
  22. // special bonus for those using jQuery
  23. if (typeof jQuery === "function" && el instanceof jQuery) {
  24. el = el[0];
  25. }
  26. var rect = el.getBoundingClientRect();
  27. return (
  28. (rect.top <= 0 && rect.bottom >= 0) ||
  29. (rect.bottom >=
  30. (window.innerHeight || document.documentElement.clientHeight) &&
  31. rect.top <=
  32. (window.innerHeight || document.documentElement.clientHeight)) ||
  33. (rect.top >= 0 &&
  34. rect.bottom <=
  35. (window.innerHeight || document.documentElement.clientHeight))
  36. );
  37. }