Skip to content
Advertisement

.clientWidth/.width in JavaScript is not working on img tag

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>

Advertisement

Answer

The browser does not have time to load the image. The clientWidth will be 0 until the image either loads or is shown as a broken image. Also, setting alt="" will always make a broken image’s clientWidth be 0 even after the browser decides that the image is broken. (In the question’s snippet, the images’ alt attributes are set this way.) This was all tested in Chrome 76.

The snippet below should work (tested in Chrome 76). I put your script in window.onload and gave the images alt attributes.

window.onload = function() {
  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="1">
		<img src="img1.png" alt="2">
		<img src="img2.png" alt="3">
		<img src="img3.png" alt="4">
		<img src="img4.png" alt="5">
		<img src="img1.png" id="firstImg" alt="6">

	</div>
</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement