Freddy
Freddy

Reputation: 867

Initializing hidden Slick.js carousel, items showing with width 0

I'm trying to initialize slick on a modal which is initially hidden.

In WordPress, I have a custom post type called experiences. I have ACF fields and trying to extract those field items and show it in a modal popup. So, the way the modal works is:

The container which houses the markup that is appended is #expHTML. This element is hidden and its inner HTML is appended to the #global-modal.

So, when I'm trying to display the images assigned to an experience post, the imgs where slick is initiliazed is showing with width: 0px.

I have tried to reinit slick on button click, but it doesn't work. Here's what I've tried:

$('.slick').slick('unslick').slick('reinit').slick();

$(window).trigger('resize');

Neither of them work and the imgs are still showing width:0

Demo:

(function($) {
  $(document).on("click", '.trigger', function(e) {

    e.preventDefault();

    var modalID = '#global-modal';
    $('.modal').removeClass('modal--open');

    $(modalID).fadeIn(200,function(){
      $(this).addClass('modal--open');
    });

    var experience_html = $("#expHTML").html();
    $(modalID).html(experience_html);
    return false;

    $('.slick').slick('unslick').slick('reinit').slick();

  });
})(window.jQuery);
.hidden{
  display: none;
}

a{
  background: lightblue;
  padding: 15px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<div id="expHTML" class="hidden">
  <div class="modal">
    <div class="slick">
      <img src="https://dummyimage.com/200X200/802380/fff.png&text=IMAGE+1"/>
      <img src="https://dummyimage.com/200X200/374cbf/ffffff.png&text=IMAGE+2"/>
      <img src="https://dummyimage.com/200X200/6ebd7e/ffffff.png&text=IMAGE+3"/>
    </div>
  </div>
</div>

<a class="trigger">Click me</a>

<!-- Modal  popup-->
<div class="modal" id="global-modal">
  <div class="modal__inner">
    <a class="modal__close"></a>
    <div class="modal__box"></div>
  </div>
</div>

Upvotes: 4

Views: 2971

Answers (1)

Ed Lucas
Ed Lucas

Reputation: 7355

It looks like you are returning from your onclick function before you attempt to reset your slideshow, which means that the reset code will never be executed.

$(document).on("click", '.trigger', function(e) {

  ...

  return false;

  $('.slick').slick('unslick').slick('reinit').slick();
});

Also, you should be able to clear up the image width issue by refreshing your slideshow after you reveal your modal contents, instead of trying to "unslick" and "reinit":

$('.slick').slick("refresh");

More information about the hidden slideshow issue: https://github.com/kenwheeler/slick/issues/235

Upvotes: 2

Related Questions