ashishsthanp

Zakra scroll to top JS function

Mar 17th, 2020
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. function scrollToTop() {
  2. var scrollToTopButton = document.getElementById( 'tg-scroll-to-top' );
  3.  
  4. /* Only proceed when the button is present. */
  5. if ( scrollToTopButton ) {
  6.  
  7. /* On scroll and show and hide button. */
  8. window.addEventListener(
  9. 'scroll',
  10. function () {
  11. if ( 500 < window.scrollY ) {
  12. scrollToTopButton.classList.add( 'tg-scroll-to-top--show' );
  13. } else if ( 500 > window.scrollY ) {
  14. scrollToTopButton.classList.remove(
  15. 'tg-scroll-to-top--show'
  16. );
  17. }
  18. }
  19. );
  20.  
  21. /* Scroll to top when clicked on button. */
  22. scrollToTopButton.addEventListener(
  23. 'click',
  24. function ( e ) {
  25. e.preventDefault();
  26.  
  27. /* Only scroll to top if we are not in top */
  28. if ( 0 !== window.scrollY ) {
  29. window.scrollTo(
  30. {
  31. top : 0,
  32. behavior: 'smooth'
  33. }
  34. );
  35. }
  36. }
  37. );
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment