carousel rotation, can not read style property from null

1

Well, I'm trying to make a carousel in JS vanilla, however, an error occurs when creating the script part for the carousel rotation

JS

//Cada Carousel
var bannersHolders = document.querySelectorAll(".banner-holder");
//Cada base para as imagens
var carousels = document.querySelectorAll(".banner-holder .carousel");
//Width e Height para definir os tamanhos dos carousels
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
//Definir width total de cada carousel
for(var iCarousels = 0; iCarousels < carousels.length; iCarousels++){
    var bannersInThis = carousels[iCarousels].querySelectorAll("figure");
    carousels[iCarousels].style.width = (bannersInThis.length * windowWidth) + "px";
    //Definir width de cada banner dentro de cada carousel
    for(var iBanners = 0; iBanners < bannersInThis.length; iBanners ++){
        bannersInThis[iBanners].style.width = windowWidth + "px";
    }
    setTimeout(function(){
        for(var iBanners = 0; iBanners < bannersInThis.length; iBanners++){
            carouselAtual.style.left = ("-" + (windowWidth * bannersInThis[iBanners])) + "px"
        }
    },5000);
}

HTML

<div class="banner-holder">
    <div class="carousel">
        <figure>
            <img src="assets/site/banners/banners_00.jpg">
            <figcaption>
            </figcaption>
        </figure>
        <figure>
            <img src="assets/site/banners/banners_01.jpg">
            <figcaption>
            </figcaption>
        </figure>
        <figure>
            <img src="assets/site/banners/banners_02.jpg">
            <figcaption>
            </figcaption>
        </figure>
        <!-- Adicionar banners com resolução entre 1440x1024 e 1920x1240 aqui -->
    </div>
</div>

CSS

*{margin:0;padding:0;list-style:none;outline:none;text-decoration:none;box-sizing:border-box;font-family:"Proza Libre",sans-serif;}
html,body{height:100%;}
.banner-holder{width:100%;height:100%;position:relative;overflow:hidden;}
.banner-holder .carousel{height:100%;position:absolute;display:flex;}
.banner-holder .carousel figure{position:relative;overflow:hidden;height:100%;}
.banner-holder .carousel img{min-width:100%;position:absolute;height:100%;left:50%;top:50%;transform:translate(-50%,-50%);}

Error

Uncaught TypeError: Cannot read property 'length' of undefined

How can I fix the problem? What caused it?

    
asked by anonymous 29.05.2017 / 16:23

1 answer

1

Testing your code the error I had was not in the length property of any of your querySelectorAll . I get carouselAtual declaration error that is in your setTimeout . I think you need to change this line of code:

carouselAtual.style.left = ("-" + (windowWidth * bannersInThis[iBanners])) + "px"

By:

bannersInThis[iBanners].style.left = "-" + windowWidth + "px";

Anyway, if the intention is for the carousel to change the image, the ideal would be to use setInterval and not setTimeout .

    
29.05.2017 / 21:07