Reputation: 11
I'm a beginner, writing a website and trying to add an image carousel into my homepage. I have 6 images displayed on screen next to each other. What I'm trying to do is move my images 1 to the left when the website is loaded so that slide1 is the first one to be displayed. Here is part of my index.html:
<div class="cover-art-carousel">
<div class="slide">
<img src="./covers/slide6.jpg" id="lastClone">
<img src="./covers/slide1.png">
<img src="./covers/slide2.png">
<img src="./covers/slide3.jpg">
<img src="./covers/slide4.jpg">
<img src="./covers/slide5.jpg">
<img src="./covers/slide6.jpg">
<img src="./covers/slide1.png" id="firstClone">
</div>
</div>
<button id="prevBtn">Prev</button>
<button id="nextBtn">Next</button>
<script src="app.js"></script>`
And this is my js:
const carouselSlide = document.querySelector('.slide');
const carouselImages = document.querySelectorAll('.slide img');
//Buttons
const prevButton = document.querySelector('#prevBtn');
const nextButton = document.querySelector('#nextBtn');
//Counter
let counter = 1;
const size = carouselImages[0].clientWidth;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
When I load the site, clientWidth is equal to 0 even though I know it should be 300. The weirdest thing is that if I add an alert into my JS, it works fine. I'm sure I'm missing something super obvious but if anyone could help that would be great. Hope this makes sense. Thanks!
Upvotes: 0
Views: 918
Reputation: 15665
wrap your js script like this:
window.onload = function(){ the rest of your js.....
}
it would seem that you may be trying to get the width before the images are loaded in.
Upvotes: 1