0

I'd like to create two functions without using jQuery to scroll from top to bottom and bottom to top with a timeout.

My code using jQuery (it works) :

function scrollToTop() {
  setTimeout(function() {
    $('html, body').animate({ scrollTop: 0 }, {
      duration: 10000,
      complete: function() {
        scrollToBottom();
      }
    });
  }, 10000);
}

function scrollToBottom() {
  setTimeout(function() {
    $('html, body').animate({ scrollTop: $(document).height() }, {
      duration: 10000,
      complete: function() {
        scrollToTop();
      }
    });
  }, 10000);
}

scrollToBottom();
tonymx227
  • 5,293
  • 16
  • 48
  • 91
  • Does this answer your question? [Vanilla JavaScript: Scroll to Top of Page](https://stackoverflow.com/questions/46234629/vanilla-javascript-scroll-to-top-of-page) – Diego D Jul 19 '22 at 08:49

2 Answers2

0

You can use this:

// top
setTimeout(() => window.scrollTo(0,0), 1000);

// bottom
setTimeout(() => window.scrollTo(0, document.body.scrollHeight), 1000);
Nicolas Menettrier
  • 1,647
  • 1
  • 13
  • 28
  • With this code I don't have an animation from top to bottom and when the scroll is setted to bottom I want to scroll to top. I'd like to create a loop from top to bottom and bottom to top. – tonymx227 Jul 19 '22 at 09:00
0

You could use the scroll method, it's a native method and also has a option for different behavior.

function scrollToTop() {
  setTimeout(function() {
    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });
  }, 10000);
}

function scrollToBottom() {
  setTimeout(function() {
    window.scroll({
      top: 1000,
      left: 0,
      behavior: 'smooth'
    });
  }, 10000);
}
Francis G
  • 1,040
  • 1
  • 7
  • 21