0

I'm trying to understand the magic behind sliders and currently following this tutorial on YT. On 8:50 he uses the clientWidth property of a slide to translate the slider-wrapper to the left by the width of one image (they are all scaled equally).

His code (and mine) looks like that:

<div class="carousel">
    <div class="carousel__item">
        <img class="test" src="../images/3.jpeg" id="last-clone"/>
        <img class="test" src="../images/1.jpeg" />
        <img class="test" src="../images/2.jpeg" />
        <img class="test" src="../images/3.jpeg" />
        <img class="test" src="../images/1.jpeg" id="first-clone"/>
    </div>
</div>

<script>
    const slidesWrapper = document.querySelector('.carousel__item');
    const slides = document.querySelectorAll('.carousel__item img');
    const size = slides[0].clientWidth;
    let counter = 1; //refers to the current active slide
    
    slidesWrapper.style.transform = `translateX(${(-size * counter)}px)`;

    console.log(slides); //when inspecting first items clientWidth, the value is correct
    console.log(`slides[0].clientWidth is ${slides[0].clientWidth}`); //logs an incorrect value
</script>

When I inspect the first console.log, the clientWidth of the first item is the correct value - it's the same value I can see, when hovering over the element in the devtools.

first items clientWidth

But when I log the value directly, it's completely different:

directly logged value

This is weird, can someone explain to me, what's happening here?

PHilgarth
  • 285
  • 1
  • 3
  • 19
  • Is this happening: [console.log() shows the changed value of a variable before the value actually changes](https://stackoverflow.com/a/48969647/14526868)? – Jesper Sep 30 '21 at 08:27
  • No, that's not the case, the first console.log and the second show different values at the same time - if it was because of the ref problem, the value in the first console.log would be 305 as well. – PHilgarth Sep 30 '21 at 09:05

0 Answers0