← Snippets - Script - Slick Slider Customization

Multiple Slick Sliders within Tabs

Why?

Slick cannot determine the width for sliders/carousels inside a hidden container. So on page load, the visible one shows fine, but the hidden ones do not until you resize the window.

What This Does

  1. Tabs are not active thru html classes like they normally should be. Instead, on page load the first tab (#tab1Title below) is shown with this script, which initializes the slider/carousel in its tab content. if the first tab is active by default with html classes, you would have to have two slick calls. So letting the tab shown event handle it is cleaner
  2. When a tab is switched
  • the carousel in the tab that was just closed gets unslicked. I saw a lot of weirdness if this wasn’t set up like this, such as slick settings below a breakpoint remaining on larger screens or carousels getting compounded each time you switched a tab.
  • the corresponding slick/carousel gets initialized

HTML

  1. Set up tabs as per BS4 instructions. Tab content or nav items do not need an active/show classes - they will get shown with the script
  2. Within each tab content, place a container that will get slicked. They can all have the same class name
  • tabs-container class used below is just an example

Script

In sliders.js add the following to the window load event.

   $('.tabs-container .nav-item').on('hidden.bs.tab', function(){
      $('.tabs-container .slick-initialized').slick('unslick');
   }).on('shown.bs.tab', function(){
      $('.tabs-container__carousel:visible').slick({
         // insert whatever Slick settings your design calls for
      });
   })

   // show the first tab's content on load, which also slicks its slider
   $('#tab1Title').tab('show');

slick, slider, javascript, js, bootstrap 4