Saturday, 25 May 2024

auto scroll up and down with random time

 Auto-scrolling a webpage up and down at random intervals between 5 to 10 seconds using JavaScript.

  1. getRandomInterval(min, max): This function generates a random interval between the provided minimum and maximum values (in seconds), converting it to milliseconds.
  2. scrollPage(): The main function that initiates the scrolling.
    • scrollHeight: The total scrollable height of the page minus the viewport height.
    • scrollAmount: The amount by which the page will scroll in each direction. Adjust this value as needed to control the scroll distance.
    • direction: A variable to keep track of the current scroll direction ('down' or 'up').
  3. performScroll(): This function handles the actual scrolling logic. It uses window.scrollBy with behavior: 'smooth' for smooth scrolling.
    • It alternates the direction of scrolling between down and up.
    • It sets a new timeout with a random interval between 5 and 10 seconds before the next scroll.
<-- code start -->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Auto Scroll Example</title> </head> <body> <!-- Your page content goes here -->
Your content height should be 700px for best performance <script> // Include the JavaScript code provided above here
function getRandomInterval(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min) * 1000;
}

function scrollPage() {
  let scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
  let scrollAmount = scrollHeight / 2; // Adjust the scroll amount as needed
  let direction = 'down';

  function performScroll() {
    if (direction === 'down') {
      window.scrollBy({
        top: scrollAmount,
        behavior: 'smooth'
      });
      direction = 'up';
    } else {
      window.scrollBy({
        top: -scrollAmount,
        behavior: 'smooth'
      });
      direction = 'down';
    }
    setTimeout(performScroll, getRandomInterval(5, 10));
  }

  setTimeout(performScroll, getRandomInterval(5, 10));
}

// Start the scrolling
scrollPage();

</script> </body> </html>