carrousel list in javascript

Here is an example of how to create a simple carousel list in JavaScript:

HTML code:

<div class="carousel">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>
</div>
125 chars
9 lines

CSS code:

.carousel {
  width: 200px; /* Set the width of the carousel container */
  overflow: hidden; /* Hide the overflow */
}
.carousel ul {
  width: 800px; /* Set the width of the list to 4 times the width of the container */
  list-style-type: none; /* Remove the bullet points */
  padding: 0; /* Remove the default padding */
  margin: 0; /* Remove the default margin */
  transition: transform 0.5s ease; /* Add a transition effect */
}
.carousel li {
  float: left; /* Float the list items */
  width: 200px; /* Set the width of each list item to the width of the container */
  height: 200px; /* Set the height of each list item */
  background-color: #ccc; /* Add a background color */
  text-align: center; /* Center the text */
  line-height: 200px; /* Center the text vertically */
}

790 chars
21 lines

JavaScript code:

const carousel = document.querySelector(".carousel ul");
const items = document.querySelectorAll(".carousel li");
const itemCount = items.length;
const margin = 10; // Change to your preferred margin
let currentIndex = 0;

function moveCarousel() {
  const itemWidth = (carousel.offsetWidth / 4) - margin; // Adjust the 4 to the number of visible items
  const moveDistance = currentIndex * (itemWidth + margin) * -1;
  carousel.style.transform = `translateX(${moveDistance}px)`;
}

// Add event listeners to prev and next buttons
document.querySelector(".prev").addEventListener("click", () => {
  currentIndex = currentIndex > 0 ? currentIndex - 1 : 0;
  moveCarousel();
});

document.querySelector(".next").addEventListener("click", () => {
  currentIndex = currentIndex < itemCount - 4 ? currentIndex + 1 : itemCount - 4;
  moveCarousel();
});

// Move to the first item on load
moveCarousel();
899 chars
26 lines

This example assumes that you want to display 4 items at a time, but you can adjust the CSS and JavaScript to display more or less items.

gistlibby LogSnag