I have a code that changes images by mouse scroll, I need to add an automatic change of images if the user does not scroll within 7 seconds
<script>
const imageContainer = document.querySelector('.image-container');
const images = document.querySelectorAll('.image');
let currentIndexScroll = 0;
let isScrolling = false;
let hasScrolled = false;
function getRandomIndex(max) {
return Math.floor(Math.random() * max);
}
document.addEventListener('wheel', (e) => {
if (isScrolling) return;
const delta = e.deltaY;
const sensitivity = 40;
if (delta > sensitivity && !hasScrolled) {
currentIndexScroll = getRandomIndex(images.length);
hasScrolled = true;
} else if (delta < -sensitivity && !hasScrolled) {
currentIndexScroll = getRandomIndex(images.length);
hasScrolled = true;
}
images.forEach((image, index) => {
if (index === currentIndexScroll) {
image.style.opacity = 1;
} else {
image.style.opacity = 0;
}
});
if (hasScrolled) {
isScrolling = true;
setTimeout(() => {
isScrolling = false;
hasScrolled = false;
}, 600);
}
});
</script>
I tried to add a timer, but the images do not change
2
Answers
Pseudo-code below:
Here’s a reusable example which uses setInverval to autoplay your images on init, and if the mouse is not hovering the images parent. Uses the Modulo operator
%
in amod
function to loop over the images. Uses simple functions likeanim()
that animates assigning an active class to thec
current index image. Usesnext()
andprev()
functions on "wheel" event to increment or decrementc
current index andanim()
animate to the current image. As a bonus, on click calls thenext()
function: