Search code examples
javascripttemplatesslidersplidejs

Does Splide work, if I insert element in DOM with tag template (vanilla JS)?


I'm training my hard skills by working on a project. I have a gallery with cards, where items are rendered with tag template in JS. So, I want to make a slider using Splide. I've copied the recommended slider structure, cards are rendered, but slider doesn't work (arrows are not clickable).

I see in DOM that the structure is rendered correctly, so no thought why it doesn't work. I've compared it to my other slider in the project and still no guess.

Could you help me please? I can't find an error by myself

    <div class="splide bicycles__gallery" aria-label="Слайдер с
    карточками велосипедов" role="group" id="bicyclesSlider">
      <div class="splide__track">
        <div class="splide__list"></div>
      </div>
    </div>
    <template class="bicycles__card-template">
      <article class="splide__slide bicycles__gallery-card">
        <a href="" target="_blank" class="bicycles__gallery-link">
          <img src="#" alt="" class="bicycles__gallery-image">
        </a>
        <h3 class="bicycles__gallery-image-caption" lang="en"></h3>
      </article>
    </template>
    const galleryBicycles = document.querySelector('.bicycles__gallery');
    const galleryBicyclesSlider = galleryBicycles.querySelector('.splide__list');
    const cardTemplateBicycle = document.querySelector('.bicycles__card-template').content;

    const bicyclesSlider = new Splide('.bicycles__gallery', {
      type: 'loop',
      perPage: 3,
      perMove: 1,
      pagination: false,
      speed: 800,
      drag: false,
      keyboard: 'focused',
      autoWidth: true,
      autoHeight: true,
      gap: 40,
        breakpoints: {
          770: {
            perPage: 1,
            keyboard: false,
          }
        }
    }).mount();

    function createCardBicycle(card) {
      const cardItem = cardTemplateBicycle.cloneNode(true);
      const cardContent = cardItem.querySelector('.bicycles__gallery- 
      card');
      <...>
      return cardItem;
     }

    function renderCardsBicycles(key) {
      Object.values(initialCardsBicycles[key]).forEach(card => {
        galleryBicyclesSlider.append(createCardBicycle(card));
      });
    }

    window.onload = () => {
      renderCardsBicycles(Object.keys(initialCardsBicycles)[0]);
    }

Solution

  • Okay, I've found the description of my situation here and here. The problem was in the tag template: JS rendered cards just after Splide had initialized his own assets, that's why the slider didn't work. So I've changed the order of switching on the scripts and carried outside the function, which renders initial cards, from the window.onload().