Vlasta Po
Vlasta Po

Reputation: 901

Carousel in Vanilla JavaScript - sliding all pictures instead of one

please, can you help me, how to make in Vanilla JS carousel, that will show 3 pictures at the same time, and when I click next button, it will slide, so first (left) will slide out of screen and to the right will slide in new one? I have tried to do it, but I have all divs stacked under, and the it slides all of them at the same time..

All the slides have set in CSS:

.slide {
    display: inline-block;
}

Here is working example on Codepen: https://codepen.io/vlastapolach/pen/zzmMOW

And here is full JS code:

var Carousel = function (frameSelector, sliderSelector, slidesSelector, btnLeftSelector, btnRightSelector) {
    //A variable to store the position of the slides
    var leftPosition = 0;
    var frame = document.querySelector(frameSelector);
    var slides = document.querySelectorAll(slidesSelector);
    //Get the number of slides in the slider
    var slidesNumber = slides.length;
    var leftButton = document.querySelector(btnLeftSelector);
    var rightButton = document.querySelector(btnRightSelector);
    var slider = document.querySelector(sliderSelector);

    //Add classes to frame and slider divs
    frame.classList.add('frame');
    slider.classList.add('slider');

    //Event listeners for when the user clicks on the arrows
    leftButton.addEventListener("click", function() {
        carousel.previous();
    });

    rightButton.addEventListener("click", function() {
        carousel.next();
    });

    //Function that moves the slides left or right depending on variable value
    //Moves to the next slide if value is -1, moves to the previous is value is 1
    var moveSlide = function (value) {
        leftPosition += value*100;
        slider.style.left = leftPosition + '%';
    };

    return {
        //Function to move to next slide
        next: function() {
            if(leftPosition > (slidesNumber-1)*-100)
            {
                moveSlide(-1);
            } else {
                leftPosition = 0;
                slider.style.left = leftPosition + '%';
            }
        },
        //Function to go to previous slide
        previous: function() {
            if(leftPosition !== 0) {
                 moveSlide(1);
            } else {
                leftPosition = (slidesNumber-1)*-100;
                slider.style.left = leftPosition + '%';
            }
        }
    };
};

//Create new instance of Carousel
var carousel = new Carousel('#frame', '#slider', '#slider .slide', '.arrowLeft', '.arrowRight');

Please, do you have any idea how to make it work? Thank you!

Upvotes: 1

Views: 939

Answers (1)

Vlasta Po
Vlasta Po

Reputation: 901

Thank you, but I managed to solve it by myself.

To the top container I had to add:

overflow: hidden;

and to the slider container:

display: inline-flex;

So it stacked all divs in one line and slider finally works.

Upvotes: 1

Related Questions