Search code examples
javascriptcsscarousel

I have a problem with a carousel, setInterval and style.transform = "translateX"


I don't understand why when the function has to show a counter it works and if I ask her to translate an element she translate it only once.

This is the code, I tried a lot but I can't find a solution:

var i; //  set your counter to 1
var numberOfImages = document.getElementsByClassName("imgs").length;
var imgWidth = window.innerWidth;
    
console.log(numberOfImages);
    
var startIt = setInterval(function() {
    document.getElementById("carouselTrain").style.transform = "translateX(" + -imgWidth + "px)";
    document.getElementById("carouselTrain").style.transitionDuration = "0.5s";
    document.getElementById("carouselTrain").style.transform = "translateX(" + -imgWidth + "px)";
    document.getElementById("carouselTrain").style.transitionDuration = "0.5s";        
}, 1000);

Solution

  • The problem is that you are translating by the same value every time. Translating doesn’t accumulate which is why you’re not seeing any changes.

    If you update the value of imgWidth in the set interval function you’ll start to see some action. Do this at the bottom of the setInterval function:

    imgWidth += imgWidth