0

I'm making a simple slider with HMTL, CSS and JS. The slides are 100% width. Is there any way to make the js move the slides 100 view width for every click? So that you only see one image at a time? Here's my code:

HTML:

 <section id="work">
    <div id="imgSliderContainer" class="imgSliderContainer">
        <div class="imgDiv" style="background-image: url(work/food2.jpg);"></div>
        <div class="imgDiv" style="background-image: url(work/Iphone_ryddeportalen_mockup.jpg);"></div>
        <button type="button" class="sliderButtonLeft" onclick="slide('left')"></button>
<button type="button" class="sliderButtonRight" onclick="slide('right')"></button>
    </div>

</section>

CSS:

.imgSliderContainer {
width: 100vw;
height: 700px;
overflow: scroll;
display: flex;
flex-wrap: nowrap;
justify-content: flex-start;
z-index: 1000;
}

.imgDiv {
min-width: 100%;
display: inline-flex;
background-size: cover;
}

JS:

 function slide(direction){
        var container = document.getElementById('imgSliderContainer');
        scrollCompleted = 0;
        var slideVar = setInterval(function(){
            if(direction == 'left'){
                container.scrollLeft -= 100;
            } else {
                container.scrollLeft += 100;
            }
            scrollCompleted += 10;
            if(scrollCompleted >= 100){
                window.clearInterval(slideVar);
            }
        }, 50);
    }
marteteigen
  • 7
  • 1
  • 6

1 Answers1

0

You can take the imgDiv width to scroll left and right

function slide(direction){
        const container = document.getElementById('imgSliderContainer');
        const imgDiv = document.querySelector(".imgDiv")
        scrollCompleted = 0;
        var slideVar = setInterval(function(){
            if(direction == 'left'){
                container.scrollLeft -= imgDiv.clientWidth;
            } else {
                container.scrollLeft += imgDiv.clientWidth;
            }
            scrollCompleted += 10;
            if(scrollCompleted >= 100){
                window.clearInterval(slideVar);
            }
        }, 50);
    }

You can learn about element clientWidth at https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth