I want to make a JavaScript slider for that I need to get the width of the images so I can apply translateX
on them but when I try to get the width of first image of the div it returns 0.
I'm pretty sure that the error is in the var size = carouselImg[0].clientWidth;
line but I don't know how to fix it. I placed the JavaScript code below the HTML.
var carouselSlide = document.querySelector(".carousel-slide");
var carouselImg = document.querySelectorAll(".carousel-slide img");
let count = 1;
var size = carouselImg[0].clientWidth;
carouselSlide.style.transform = 'translateX(' + (-size * count) + 'px)';
console.log(size);
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.carousel-container{
width: 900px;
border: 3px solid black;
margin: auto;
}
.carousel-slide{
display: flex;
height: 300px;
}
<div class="carousel-container">
<div class="carousel-slide">
<img src="img4.png" id="lastImg" alt="">
<img src="img1.png" alt="">
<img src="img2.png" alt="">
<img src="img3.png" alt="">
<img src="img4.png" alt="">
<img src="img1.png" id="firstImg" alt="">
</div>
</div>