Creating a Carousel in JS

Hi guys I am trying to create a Carousel using JS. I have succeeded a bit and I able to move one slide to the right side. I figure if I somehow increase the value of widthToMove variable then by clicking on right arrow button will keep pushing the slides. I tried to create a function that returns simply 1, 2, 3, and so on and multiply it with widthToMove on clicking right arrow button but I could not succeed. Any help will highly be appreciated. Here is the html code;

var productDataWomens = [
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/coats-jackets/dark-grey-faux-fur-longline-coat/p/619712403',
    imageSrc: 'https://media2.newlookassets.com/i/newlook/619712403.jpg',
    productTitle: 'Dark Grey Faux Fur Longline Coat',
    price: '45.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/tops/black-ribbed-long-sleeve-roll-neck-top/p/635105501',
    imageSrc: 'https://media2.newlookassets.com/i/newlook/635105501.jpg',
    productTitle: 'Black Ribbed Long Sleeve Roll Neck Top',
    price: '8.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/leggings/black-coated-leather-look-leggings/p/634018201',
    imageSrc: 'https://media3.newlookassets.com/i/newlook/634018201.jpg',
    productTitle: 'Black Coated Leather-Look Leggings',
    price: '19.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/coats-jackets/black-faux-fur-longline-coat/p/619712401',
    imageSrc: 'https://media3.newlookassets.com/i/newlook/619712401.jpg',
    productTitle: 'Black Faux Fur Longline Coat',
    price: '45.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/jeans/black-high-waist-super-skinny-hallie-jeans/p/635654901',
    imageSrc: 'https://media2.newlookassets.com/i/newlook/635654901.jpg',
    productTitle: 'Black High Waist Super Skinny Hallie Jeans',
    price: '25.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/coats-jackets/formal-coats/camel-revere-collar-coat/p/619653214',
    imageSrc: 'https://media2.newlookassets.com/i/newlook/619653214.jpg',
    productTitle: 'Camel Revere Collar Coat',
    price: '35.99',
  }
]



for (i in productDataWomens) {
  var node = document.createElement('LI');

  node.setAttribute('class', 'carousel-list-item' + ' ' + 'current-slide');

  var carouselImg = document.createElement('img');
  carouselImg.setAttribute('class', 'carousel-images');
  carouselImg.src = productDataWomens[i].imageSrc;

  node.appendChild(carouselImg);
  document.getElementById('carousel-list-id').appendChild(node);
}

const track = document.querySelector('.carousel-list-items');
console.log(track);
const slides = Array.from(track.children);
console.log(slides);
const nextButton = document.querySelector('.right-button');
const prevButton = document.querySelector('.left-button');

const slideWidth = slides[0].getBoundingClientRect().width;

nextButton.addEventListener('click', (e) => {
  let currentSlide = track.querySelector('.current-slide');
  console.log(currentSlide);

  let widthToMove = currentSlide.clientWidth;
  console.log(slides[0]);

  widthToMove = widthToMove + 'px';
  console.log(widthToMove);

  let nextSlide = currentSlide.nextElementSibling;
  console.log(nextSlide);
  //const amountToMove = nextSlide.style.widthToMove;
  track.style.transform = 'translateX(-' + widthToMove + ')';
  currentSlide.classList.remove('current-slide');
  //nextSlide.classList.add('current-slide');
});
.carousel {
  display: flex;
  justify-content: space-between;
  /* overflow-x: hidden; */
  width: 80%;
  margin: 0 auto;
}

.carousel-list-items {
  display: flex;
  justify-content: space-between;
}

.carousel-container {
  overflow-x: hidden;
}

.carousel-list {
  list-style: none;
}

.carousel-images {
  padding: 15px;
  height: 200px;
}

.carousel-button {
  position: relative;
  background-color: transparent;
  border: none;
  cursor: pointer;
  outline: 0;
}

.right-button {
  right: 0;
  margin-left: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://kit.fontawesome.com/88ce2b0d97.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="styles.css">
    <title>New Look</title>
</head>
<body>
    <div class="carousel">
        <button class="left-button carousel-button"><i class="fas fa-chevron-left"></i></button>
        <div class="carousel-container" >
            <ul class="carousel-list">
                <a href="" id="carousel-list-id" class="carousel-list-items">
                     <!-- <li class="carousel-list-item current-slide" id="carousel-list-id"></li> -->
                </a>
            </ul>
            
        </div>
        <button class="right-button carousel-button"><i class="fas fa-chevron-right"></i></button>
    </div>
    
    <script src="script.js"></script>
    </script>
</body>
</html>

Answer

The problem with your slider is that each time you click on the next button the widthToMove variable is overwritten with currentSlide.clientWidth, what you should’ve done instead is:

  1. take widthToMove variable outside the scope of the listener
  2. on each click add the values of widthToMove and currentSlide.clientWidth and assign the sum to widthToMove

Also when your slider is “initialized”, every slide has the class current-slide therefore you can’t determine which slide is the current.

var productDataWomens = [
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/coats-jackets/dark-grey-faux-fur-longline-coat/p/619712403',
    imageSrc: 'https://media2.newlookassets.com/i/newlook/619712403.jpg',
    productTitle: 'Dark Grey Faux Fur Longline Coat',
    price: '45.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/tops/black-ribbed-long-sleeve-roll-neck-top/p/635105501',
    imageSrc: 'https://media2.newlookassets.com/i/newlook/635105501.jpg',
    productTitle: 'Black Ribbed Long Sleeve Roll Neck Top',
    price: '8.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/leggings/black-coated-leather-look-leggings/p/634018201',
    imageSrc: 'https://media3.newlookassets.com/i/newlook/634018201.jpg',
    productTitle: 'Black Coated Leather-Look Leggings',
    price: '19.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/coats-jackets/black-faux-fur-longline-coat/p/619712401',
    imageSrc: 'https://media3.newlookassets.com/i/newlook/619712401.jpg',
    productTitle: 'Black Faux Fur Longline Coat',
    price: '45.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/jeans/black-high-waist-super-skinny-hallie-jeans/p/635654901',
    imageSrc: 'https://media2.newlookassets.com/i/newlook/635654901.jpg',
    productTitle: 'Black High Waist Super Skinny Hallie Jeans',
    price: '25.99',
  },
  {
    productUrl:
      'https://www.newlook.com/uk/womens/clothing/coats-jackets/formal-coats/camel-revere-collar-coat/p/619653214',
    imageSrc: 'https://media2.newlookassets.com/i/newlook/619653214.jpg',
    productTitle: 'Camel Revere Collar Coat',
    price: '35.99',
  }
]



for (i in productDataWomens) {
  var node = document.createElement('LI');
  
  // If it's the first slide add .current-slide
  // The line below uses a turnary operator which is a short if/else statement
  var currentSlide = ( i == 0 ? ' current-slide' : '' );
  
  // Which can be rewritten to this
  //var currentSlide;
  
  //if( i == 0 ) {
  //  currentSlide == ' current-slide';
  //} else {
  //  currentSlide == '';
  //}
  
  

  node.setAttribute('class', 'carousel-list-item' + currentSlide );

  var carouselImg = document.createElement('img');
  carouselImg.setAttribute('class', 'carousel-images');
  carouselImg.src = productDataWomens[i].imageSrc;

  node.appendChild(carouselImg);
  document.getElementById('carousel-list-id').appendChild(node);
}

const track = document.querySelector('.carousel-list-items');

const nextButton = document.querySelector('.right-button');
const prevButton = document.querySelector('.left-button');

let widthToMove = 0;


nextButton.addEventListener('click', (e) => {
  let currentSlide = track.querySelector('.current-slide');
  let nextSlide;
  
  if( !currentSlide.nextElementSibling ) {
    nextSlide = document.querySelectorAll('.carousel-list-item')[0];
    widthToMove = 0;
  } else {
    nextSlide = currentSlide.nextElementSibling;
    widthToMove += currentSlide.clientWidth;
  }
  

  // You can use template literals to create a string with several variables/functions/expressions for speed, convenience and readability
  track.style.transform = `translateX(-${widthToMove + 30}px)`;
  currentSlide.classList.remove('current-slide');
  // Add current-slide class to next slide
  nextSlide.classList.add('current-slide');
});
.carousel {
  display: flex;
  justify-content: space-between;
  /* overflow-x: hidden; */
  width: 80%;
  margin: 0 auto;
}

.carousel-list-items {
  display: flex;
  justify-content: space-between;
  transition: all 0.3s ease-in-out 0s;
}

.carousel-container {
  overflow-x: hidden;
}

.carousel-list {
  list-style: none;
}

.carousel-images {
  padding: 15px;
  height: 200px;
}

.carousel-button {
  position: relative;
  background-color: transparent;
  border: none;
  cursor: pointer;
  outline: 0;
}

.right-button {
  right: 0;
  margin-left: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://kit.fontawesome.com/88ce2b0d97.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="styles.css">
    <title>New Look</title>
</head>
<body>
    <div class="carousel">
        <button class="left-button carousel-button"><i class="fas fa-chevron-left"></i></button>
        <div class="carousel-container" >
            <ul class="carousel-list">
                <a href="" id="carousel-list-id" class="carousel-list-items">
                     <!-- <li class="carousel-list-item current-slide" id="carousel-list-id"></li> -->
                </a>
            </ul>
            
        </div>
        <button class="right-button carousel-button"><i class="fas fa-chevron-right"></i></button>
    </div>
    
    <script src="script.js"></script>
    </script>
</body>
</html>