Using buttons to scroll through a carousel

Viewed 32

I have created a carousel where each slide contains different content. Currently, the only way to go to the next item is to click a little button at the bottom of the carousel.

I have added the buttons with the id nextBtn and prevBtn.

I want to add buttons on the side to navigate through the carousel. The previous/next carousel slide should appear on the screen when the button is pressed, and keep the 3 little buttons on the bottom of the container.

see image

Here is my current HTML:

<div class="carousel">
  <div class="carousel__item item-one">
    <div class="carousel-text">
        <h1>Make your business</h1>
        <h1>shine online</h1>
    </div>
  </div>
  <div class="carousel__item item-two">
    <div class="carousel-text">
        <h2>Make your business</h2>
        <h2>shine online</h2>
    </div>
  </div>
  <div class="carousel__item item-three">
      <div class="carousel-text">
        <h2>Make your business</h2>
        <h2>shine online</h2>
    </div>
  </div>
  <button id="prevBtn">prev</button>
  <button id="nextBtn">next</button>
</div>

JavaScript:

document.querySelectorAll(".carousel").forEach((carousel) => {
  const items = carousel.querySelectorAll(".carousel__item");
  const buttonsHtml = Array.from(items, () => {
    return `<span class="carousel__button"></span>`;
  });

  carousel.insertAdjacentHTML(
    "beforeend",
    `
        <div class="carousel__nav">
            ${buttonsHtml.join("")}
        </div>
    `
  );

  const buttons = carousel.querySelectorAll(".carousel__button");

  buttons.forEach((button, i) => {
    button.addEventListener("click", () => {
      // un-select all the items
      items.forEach((item) =>
        item.classList.remove("carousel__item--selected")
      );
      buttons.forEach((button) =>
        button.classList.remove("carousel__button--selected")
      );

      items[i].classList.add("carousel__item--selected");
      button.classList.add("carousel__button--selected");
    });
  });

  // Select the first item on page load
  items[0].classList.add("carousel__item--selected");
  buttons[0].classList.add("carousel__button--selected");
});
0 Answers
Related