JavaScript Image Carousel Tutorial

To achieve a scrolling effect for images, you can use JavaScript in combination with CSS. Here is a simple example:

HTML section:

<div id="imageSlider">
    <img src="image1.jpg" alt="Image 1">
    <img src="image2.jpg" alt="Image 2">
    <img src="image3.jpg" alt="Image 3">
</div>

CSS section:

#imageSlider {
    width: 300px;
    height: 200px;
    overflow: hidden;
}

#imageSlider img {
    width: 100%;
    height: 100%;
    display: inline-block;
}

JavaScript section:

let imageIndex = 0;
const images = document.querySelectorAll('#imageSlider img');
const totalImages = images.length;

function showImage(index) {
    images.forEach((image) => {
        image.style.display = 'none';
    });
    images[index].style.display = 'block';
}

function slide() {
    imageIndex = (imageIndex + 1) % totalImages;
    showImage(imageIndex);
}

setInterval(slide, 2000);

In the example above, the continuous scrolling effect of the images is achieved by repeatedly calling the slide function using a timer. The showImage function is used to display the image at a specified index, while the slide function increments the imageIndex by 1 each time and uses modulo operation to enable the looping effect.

bannerAds