// Select DOM elements const imageContainer = document.getElementById('image-container'); const images = document.querySelectorAll('img'); // Create a index counter let index = 0; // Set the function runCarousel to be called // every 4 seconds let interval = setInterval(runCarousel, 4000); function runCarousel() { index++ // increase index by 1 checkOutBoundConditions() changeImage() // change image to new index value } function checkOutBoundConditions() { // If index reaches the end, set // index to 0 again (recall index // starts from 0) if(index === images.length) { index = 0 } // If index is less than 0, set // to 0 else if (index < 0) { index = 0 } } function changeImage() { // Negative value on translateX shifts images left, // so show animates by multiplying the width of an // image by index value imageContainer.style.transform = `translateX(${-index * 600}px)` } const prevBtn = document.getElementById('previous'); const nextBtn = document.getElementById('next'); nextBtn.addEventListener('click', () => { // reset interval clearInterval(interval); interval = setInterval(runCarousel, 3000); // increase counter by 1 index++; // Run index value through out of bounds // check and then run change image with nex // index value checkOutBoundConditions(); changeImage() }) prevBtn.addEventListener('click', () => { // reset interval clearInterval(interval); interval = setInterval(runCarousel, 3000); // decrease counter by 1 index--; // Out of bounds check and then change image // with new index value checkOutBoundConditions(); changeImage() });
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter