🛠 Carousel: Positioning slides with JavaScript

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

🛠 Carousel: Positioning slides with JavaScript

For the carousel we built so far, the width of each slide is fixed to 800px. This is unacceptable. We want our carousel to be responsive.

For our carousels to be responsive, we need to let our user’s browsers determine the width of each slide.

For this to happen, let’s change the 800px limit to 80vw. This means 80% of the browser’s viewport width.

/* Change this */
.carousel {
  grid-template-columns: 3em 800px 3em;
}

/* To this */
.carousel {
  grid-template-columns: 3em 80vw 3em;
}

Here’s what you might see:

Second slide overlaps the first slide.

In this case, 80vw in my browser is larger than 800px. The second slide is set to 800px. It overlaps the first slide because of this.

We can no longer position slides with CSS. We need to position slides with JavaScript.

Positioning the slides with JavaScript

First, let’s remove slide positions we wrote in the CSS:

/* Remove these */
.carousel__slide:nth-child(2) {
  left: 800px;
}

.carousel__slide:nth-child(3) {
  left: 1600px;
}

From the previous lessons, we know these:

  1. left of second slide should be one slide’s width.
  2. left of third slide should be two slide’s width.

We need to find the width of one slide first. We can get the width of one slide with getBoundingClientRect. In this case, Getting the width of the first slide is sufficient.

const rect = slides[0].getBoundingClientRect()
console.log(rect)
DOMRect of the first slide.

We can get the width of one slide with the width property from getBoundingClientRect.

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

console.log(slideWidth) // 936 (This may be a different number in your case. It depends on the width of your browser).

You can shorten the code above slightly by chaining properties together.

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

Next, we want to position the slides with JavaScript.

  • First slide’s left should be 0px
  • Second slide’s left should be slideWidth
  • Third slide’s left should be two slideWidths
slides[0].style.left = '0px'
slides[1].style.left = slideWidth + 'px'
slides[2].style.left = slideWidth * 2 + 'px'

To make the calculations consistent, you can substitute the above with this:

slides[0].style.left = slideWidth * 0 + 'px'
slides[1].style.left = slideWidth * 1 + 'px'
slides[2].style.left = slideWidth * 2 + 'px'

Notice we can use the index of each slide to calculate the correct left value? Since you see this pattern now, let’s switch to a forEach loop to position the slides.

slides.forEach((slide, index) => {
  slide.style.left = slideWidth * index + 'px'
})
Slides positioned properly.

That’s it!