Creating a Continuous Loop Carousel with Four Divs in View
68 views
To ensure that you always have 4 div
s in view and they scroll seamlessly in a loop, you can achieve this by appending additional clones of the first few slides to the end of the carousel. This will create a continuous loop effect. Here’s how you can implement it:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Carousel</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="carousel">
<div class="slides">
<div class="slide">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
<div class="slide">4</div>
<div class="slide">5</div>
<div class="slide">6</div>
<div class="slide">7</div>
<!-- Cloning first 4 slides to create seamless loop -->
<div class="slide">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
<div class="slide">4</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS (styles.css):
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.carousel {
overflow: hidden;
width: 80vw;
}
.slides {
display: flex;
transition: transform 0.5s ease-in-out;
}
.slide {
min-width: 20vw; /* Ensure 4 slides fit into the view when the container width is 80vw */
padding: 20px;
box-sizing: border-box;
background: #4CAF50;
color: white;
text-align: center;
font-size: 20px;
border: 2px solid #fff;
user-select: none;
}
JavaScript (script.js):
const slides = document.querySelector('.slides');
const totalSlides = slides.children.length;
let index = 0;
function showNextSlide() {
index++;
if (index === totalSlides - 3) { // If we reach the end of the unlooped slides
slides.style.transition = 'none'; // Disable transition
slides.style.transform = `translateX(${index * -20}vw)`;
// Slightly delay setting index to create seamless loop effect
setTimeout(() => {
index = 0;
slides.style.transition = 'transform 0.5s ease-in-out'; // Re-enable transition
slides.style.transform = `translateX(0vw)`;
}, 50);
} else {
const offset = index * -20;
slides.style.transform = `translateX(${offset}vw)`;
}
}
setInterval(showNextSlide, 3000); // Change slide every 3 seconds
Explanation:
- HTML: The structure includes the original 7 slides plus clones of the first 4 slides to create the seamless loop.
- CSS: The styles ensure that only 4 slides fit within the view at a time, and each slide’s width is set to 20vw.
- JavaScript: The script updates the transform property for the slide container to scroll horizontally. When it reaches the end of the original slides, it quickly jumps back to the start to create a seamless loop effect.
This setup will create an infinite scrolling effect with always 4 div
s in view, ensuring a continuous carousel experience.