Search code examples
javascriptcarousel

GliderJS how to add item at a specific index in the carousel?


I am using gliderJS to create a carousel and I need to dynamically add and remove items from and to it.

I managed to get it working with the .addItem and .removeItem() methods, and while the removeItem supports removing from specific index, I dont see any way in the documentation to addItem at a specific index, does anyone know if that is possible?

This is the code so far about adding:

const elementHTML = "somehtml";
const element = document.createElement("div");
element.innerHTML = elementHTML;

glider.addItem(element);

And that adds it at the end of the carousel, I want to add it at a specific index.


Solution

  • There is no exposed api to specifically do this. However, you can change the contents of the glider and call refresh, which is indeed exactly what the addItem method does:

      gliderPrototype.addItem = function (ele) {
        var _ = this
    
        _.track.appendChild(ele)
        _.refresh(true)
        _.emit('add')
      }
    

    So in theory, you should be able to add a child to a specific index in the track and call refresh, sorta like this:

    const glider = new Glider(document.querySelector('.glider'), {
      slidesToShow: 5,
      slidesToScroll: 5,
      draggable: true
    })
    
    
    
    function insertBeforeIndex (element, index) {
      glider.track.insertBefore(element, glider.track.children[index])
      glider.refresh()
    }
    
    const newElement = document.createElement("div")
    newElement.innerHTML = "<em>new item</em>"
    
    insertBeforeIndex(newElement, 2) // inserts it in 3rd place
    .box {
      border: 2px solid lightblue;
    }
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/glider-js@1/glider.min.css">
    <script src="https://cdn.jsdelivr.net/npm/glider-js@1/glider.min.js"></script>
    
    <div class="glider-contain">
      <div class="glider">
        <div class="box"> 1 </div>
        <div class="box"> 2 </div>
        <div class="box"> 3 </div>
        <div class="box"> 4 </div>
      </div>
    </div>