Search code examples
javascripthtmlslidercarouselautoplay

Implementing Autoplay on glider.js


So I'm working with glider.js (https://nickpiscitelli.github.io/Glider.js/) on my website for handling slides, because I really want to keep it minimal (I know there are other sliders out there, but glider.js is the lightest). However, I really need the autoplay function, but I can't seem to be able to make it work (I don't really know my way around JS, I just copy code snippets for things I need)

I found some code for an autoplay, it looks like this:

function sliderAuto(slider, miliseconds) {
 slider.isLastSlide = function() {
   return slider.page >= slider.dots.childElementCount - 1;
 }

 var slide = function() {
   slider.slideTimeout = setTimeout(function() {
     function slideTo() {
       return slider.isLastSlide() ? 0 : slider.page + 1;
     }

     slider.scrollItem(slideTo(), true);
   }, miliseconds);
 }

 slider.ele.addEventListener('glider-animated', function(event) {
   window.clearInterval(slider.slideTimeout);
   slide();
 });

 slide();
}

But I don't know how to activate it, to make it work. I know I should pass the parameters to "slider" and "miliseconds", but I don't know what exactly should I pass, should I set a special class to each slide, and pass that class? Let's say my html is the following:

<div class="glider-contain">
  <div class="glider">
    <div>your content here</div>
    <div>your content here</div>
    <div>your content here</div>
    <div>your content here</div>
  </div>

How do I make the autoplay work? Thanks!


Solution

  • Based on the docs that you've linked and the code snippet i would say that First things first, slider parameter is supposed to be your glidder object (what you created with new Glidder(..., and milliseconds is the amount of time in milliseconds that each slide will be visible.

    Now, an example of what it could look like:

    <div class="glider-contain">
      <div id="glider" class="glider">
        <div class="placeholder">1</div>
        <div class="placeholder">2</div>
        <div class="placeholder">3</div>
        <div class="placeholder">4</div>
      </div>
    </div>
    
    const glider = new Glider(document.getElementById('glider'));
    
    function sliderAuto(slider, miliseconds) {
     const slidesCount = slider.track.childElementCount;
     let slideTimeout = null;
     let nextIndex = 1;
    
     function slide () {
       slideTimeout = setTimeout(
         function () {
           if (nextIndex >= slidesCount ) {
             nextIndex = 0;
           }
           slider.scrollItem(nextIndex++);
         },
         miliseconds
       );
     }
    
     slider.ele.addEventListener('glider-animated', function() {
       window.clearInterval(slideTimeout);
       slide();
     });
    
     slide();
    }
    
    sliderAuto(glider, 1000)
    

    I've edited the snippet a bit because you don't seem to use dots. working fiddle