Spaces:
Running
Running
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Scroll Image Change</title> | |
<link rel="stylesheet" href="style.css"> | |
</head> | |
<body> | |
<!-- Container for all the images --> | |
<div class="image-container"> | |
<!-- Content inside each section (if any) will be added here --> | |
</div> | |
<!-- JavaScript to handle scrolling --> | |
<script> | |
const numImages = 240; // Number of images | |
const imageContainer = document.querySelector('.image-container'); | |
// Preload all images | |
function preloadImages() { | |
for (let i = 1; i <= numImages; i++) { | |
const img = new Image(); | |
const imageNumber = String(i).padStart(4, '0'); | |
img.src = `images/${imageNumber}.png`; | |
} | |
} | |
// Call preloadImages when the page loads | |
window.onload = preloadImages; | |
// Function to get the correct image number based on scroll position | |
function getImageForScroll(scrollPos) { | |
let imageIndex = Math.floor(scrollPos / 20); // Change every 20 pixels | |
return imageIndex < numImages ? String(imageIndex + 1).padStart(4, '0') : String(numImages).padStart(4, '0'); | |
} | |
// Handle scrolling | |
window.addEventListener('scroll', () => { | |
const scrollPos = window.scrollY; // Get the scroll position | |
const imageNumber = getImageForScroll(scrollPos); // Determine which image to show | |
// Only update the background if the image is different to avoid re-rendering the same image | |
const currentImage = imageContainer.style.backgroundImage; | |
const newImage = `url('images/${imageNumber}.png')`; | |
if (currentImage !== newImage) { | |
imageContainer.style.backgroundImage = newImage; // Set the background | |
} | |
}); | |
// Set the initial background image | |
imageContainer.style.backgroundImage = `url('images/0001.png')`; | |
</script> | |
</body> | |
</html> | |