Skip to content Skip to sidebar Skip to footer

Problem With Creating Loop For Carousel - Back To First Element

I'm having issue with creating loop inside carousel so it will go back to first card after reaching last one on a click event - rightButton. So far carousel stops when reach last c

Solution 1:

You need to handle when your offset is equal to the maxX, and reset the offset back to zero.

rightButton.addEventListener("click", function() {
  if (offset !== maxX) {
    offset -= carouselWidth + cardMarginRight;
    carousel.style.transform = `translateX(${offset}px)`;
  } else {
    offset = 0;
    carousel.style.transform = `translateX(${offset}px)`;
  }
})

Solution 2:

This will use fixed widths with a gap of 10px (see CSS) - (to make it responsive you should modify the px used in JS to translate in % steps). Also, it will work for any number of .Carousel elements on the page. Also, simplify the HTML markup as per below, which is more consistent with the CSS for a better modular methodology

constCarousel = (EL) => {
  constCARDS = EL.querySelector(".Carousel-cards");
  constPREV = EL.querySelector(".Carousel-prev");
  constNEXT = EL.querySelector(".Carousel-next");
  const w = EL.offsetWidth;
  const d = CARDS.offsetWidth - w; // widths difflet x = 0;
  
  constanim = (dir) => {
    x += w * dir;
    x = Math.min(d, Math.max(0, x));
    CARDS.style.transform = `translateX(-${x}px)`;
  };
  
  PREV.addEventListener("click", () =>anim(-1)) 
  NEXT.addEventListener("click", () =>anim(+1))
};
document.querySelectorAll(".Carousel").forEach(Carousel);
.Carousel {
  height: 100px;
  width: 430px;  /*  (100px * 4) + (10px * 3gap)  */position: relative;
  overflow: hidden;
  margin: 0 auto;
}

.Carousel-nav {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: absolute;
}

.Carousel-cards {
  position: absolute;
  left: 0;
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
  transition: transform 1s ease;
  gap: 10px;
}

.Carousel-cards > * {
  background: black;
  min-width: 100px;
  height: 100px;
}

span {
  color: #ffffff;
}
<divclass="Carousel"><ulclass="Carousel-cards"><li><span>1</span></li><li><span>2</span></li><li><span>3</span></li><li><span>4</span></li><li><span>5</span></li><li><span>6</span></li><li><span>7</span></li><li><span>8</span></li><li><span>9</span></li></ul><divclass="Carousel-nav"><buttonclass="Carousel-prev">L</button><buttonclass="Carousel-next">R</button></div></div>

There's more to improve, i.e: makes no sense to have buttons if the content does not require animating, or one of the buttons depending if a direction is completed.

Post a Comment for "Problem With Creating Loop For Carousel - Back To First Element"