scroll

mail@pastecode.io avatar
unknown
javascript
a month ago
2.0 kB
1
Indexable
Never
// Get the container element that holds the images
var container = document.querySelector(".container");
// Get the width of the container element
var containerWidth = container.offsetWidth;
// Get the width of one image
var imageWidth = containerWidth / 4;
// Set the initial scroll position to zero
var scrollPosition = 0;
// Set the scroll direction to right
var scrollDirection = "right";
// Set the scroll speed in pixels per second
var scrollSpeed = 100;
// Create a function that updates the scroll position every frame
function scrollImages() {
  // Request the next frame
  requestAnimationFrame(scrollImages);
  // Calculate the elapsed time since the last frame in seconds
  var elapsedTime = (performance.now() - lastTime) / 1000;
  // Update the last time
  lastTime = performance.now();
  // Calculate the scroll distance based on the speed and the elapsed time
  var scrollDistance = scrollSpeed * elapsedTime;
  // Check the scroll direction
  if (scrollDirection == "right") {
    // Increment the scroll position by the scroll distance
    scrollPosition += scrollDistance;
    // Check if the scroll position reaches the end of the container
    if (scrollPosition >= containerWidth - imageWidth) {
      // Set the scroll position to the end of the container
      scrollPosition = containerWidth - imageWidth;
      // Change the scroll direction to left
      scrollDirection = "left";
    }
  } else {
    // Decrement the scroll position by the scroll distance
    scrollPosition -= scrollDistance;
    // Check if the scroll position reaches the start of the container
    if (scrollPosition <= 0) {
      // Set the scroll position to zero
      scrollPosition = 0;
      // Change the scroll direction to right
      scrollDirection = "right";
    }
  }
  // Set the scroll position of the container element
  container.scrollLeft = scrollPosition;
}
// Get the current time
var lastTime = performance.now();
// Call the scroll function for the first time
scrollImages();
Leave a Comment