Using slick.js in autoplay mode for a single slide

4.6k Views Asked by At

I want to use slick.js for a simple news ticker. So I have a box where text is coming from the right and automatically scrolls to the left in a loop. The problem is that slick.js refuses to move the text if there is just one slide. I want the slide to move from the right to the left and after passing the left edge it should start moving from the right again. Does anyone know how to achieve this? Here is a little fiddle showing my problem. It uses this javascript code:

$(function(){
    $('.slider').slick({
        speed: 10000,
        autoplay: true,
        autoplaySpeed: 0,
        cssEase: 'linear',
        slidesToShow: 1,
        slidesToScroll: 1,
        variableWidth: true,
        infinite: true
    });
});
2

There are 2 best solutions below

2
Jon Uleis On BEST ANSWER

Looks like slick carousel isn't built to work with only one element. How about using jQuery to clone your slide once so the plugin works? See functional example below:

$(function() {
  if ($('.slider div').length == 1) {
      $('.slider div').clone().appendTo('.slider');
  }
  $('.slider').slick({
    speed: 10000,
    autoplay: true,
    autoplaySpeed: 0,
    cssEase: 'linear',
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true,
    infinite: true
  });
});
img {
  margin: 10px;
  border: 1px solid black;
}
<link rel="stylesheet" type="text/css" href="http://kenwheeler.github.io/slick/slick/slick.css">
<link rel="stylesheet" type="text/css" href="http://kenwheeler.github.io/slick/slick/slick-theme.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://kenwheeler.github.io/slick/slick/slick.js"></script>

<section class="slider">
  <div>
    <img src="http://placehold.it/350x150" />
  </div>
</section>

0
Dovis On

Jon's answer is good, but it will give you two same slides which you can slide (change). If you wish to show single slide without cloning, you can use initialSlide setting.

$(function() {
    var start = 0;

  if ($('.slider div').length == 1) {
      start = -1;
  }

  $('.slider').slick({
    speed: 10000,
    autoplay: true,
    autoplaySpeed: 0,
    cssEase: 'linear',
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true,
    infinite: true,
    initialSlide: start
  });
});