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.
But when I log the value directly, it's completely different:
This is weird, can someone explain to me, what's happening here?