Meteor with iron-router cant get slick carousel working
Asked Answered
A

2

4

I am using iron-router, i have a route "models" which has a list of items. When the user clicks one of these items a new route "model" is used, the name of the selected item is passed as a param and used to load data about that model from the database.

I want to use slick carousel, using an array of images returned from the database (based on the param).

<div id="carousel">
    {{#each images}}
    <div class="item">
        <img src="/images/{{this}}" alt="">
    </div>
    {{/each}}
</div>

Where should I call the slick init?

Anselmo answered 9/5, 2015 at 13:0 Comment(0)
L
9

Generally speaking, you should initialize plugins in a template's onRendered callback. In your case, that won't work because onRendered will fire before any of the images are inserted into the DOM. With other carousel plugins I've seen, the following strategy works:

  1. Move each item to its own template (carouselItem).
  2. Add an onRendered callback to carouselItem so that the plugin will be initialized after each item is added to the DOM.

I haven't tried this with slick carousel, but it would look something like this:

<template name="carousel">
  <div id="carousel">
    {{#each images}}
      {{> carouselItem}}
    {{/each}}
  </div>
</template>

<template name="carouselItem">
  <div class="item">
    <img src="/images/{{this}}">
  </div>
</template>
Template.carouselItem.onRendered(function() {
  $('#carousel').slick();
});

Assuming slick carousel can be initialized multiple times, this approach should work. Be aware that one possible downside is that the plugin will refresh whenever images is updated. One way to fix that is to use the {reactive: false} option in your find.

Levenson answered 9/5, 2015 at 17:40 Comment(1)
sorry it took me so long to check, but this worked like a charm!Anselmo
P
1

Usually you would call a plugin on an element in Template.myTemplate.onRendered:

Template.xxx.onRendered(function() {
  $('#carousel').slick();
});`
Pool answered 9/5, 2015 at 14:47 Comment(2)
I have tried this and it still seems to not work, i've checked with a simple console.log that the onRendered callback is firing...Anselmo
I suspect the challenge here is that the plugin probably needs to be initialized after the images have been added to the DOM. If the plugin can be initialized multiple times, you could move each item to a sub-template and then initialize SC in each sub-template's onRendered.Levenson

© 2022 - 2024 — McMap. All rights reserved.