Sleek Carousel failing to display in Bootstrap5 Tab panel

When integrating the slick slider with Bootstrap5 Nav, I encountered an issue where the slider does not display within the active tab content unless the window is resized. Rearranging the sequence of embedded JavaScript did not solve the problem and actually caused the slider to break.

The slider works fine with pure text but encounters issues with the slick slider. This appears to be related to the JavaScript used by Bootstrap and Slick.

If you want to check out the code, here is the link: https://codepen.io/HarperJ/pen/XWqrBem

Appreciate any help in advance.

HTML:

<div class="container mt-5">
  <div class="row justify-content-center">
    <div class="col-8">
      <ul class="nav solution_nav mb-5">
            <li class="nav-item">
                <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab_1" type="button" role="tab" aria-selected="false">TAB 1</button>
            </li>
            <li class="nav-item">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab_2" type="button" role="tab" aria-selected="false">TAB 2</button>
            </li>
        
        </ul>
        <div class="tab-content">
          <div class="tab-pane fade show active" id="tab_1" role="tabpanel">
            
            <div class="slider slider-for">
              <img src='...' alt=''>
              <img src='...' alt=''>
              <img src='...' alt=''>
              <img src='...' alt=''>
            </div>
            <div class="slider slider-nav">
              <img src='...' alt=''>
              <img src='...' alt=''>
              <img src='...' alt=''>
              <img src='...' alt=''>
            </div>
            
          </div>
          <div class="tab-pane fade" id="tab_2" role="tabpanel">
            
            <div class="slider slider-for2">
              <img src='...' alt=''>
              <img src='...' alt=''>
      
            </div>
            <div class="slider slider-nav2">
              <img src='...' alt=''>
              <img src='...' alt=''>
      
            </div>
            
          </div>
        </div>
    </div>
  </div>
</div>

CSS:

*,
*::before,
*::after {
    box-sizing: border-box;
}

img {
    max-width: 100%;
    height: auto;
    display: block;
}

.solution_nav .nav-link {
    border: none;
    background: none;
    cursor: pointer;
    position: relative;
    color: #ddd;
    padding: 16px 40px;
}
.solution_nav .nav-link.active{
  color: #343434;
  border-bottom: 1px solid #343434;
}

JS:

$(document).ready(function(){
    // Slider for Tab 1
    $('.slider-for').slick({
      slidesToShow: 1,
      slidesToScroll: 1,
      arrows: false,
      fade: true,
      asNavFor: '.slider-nav'
  });
  $('.slider-nav').slick({
      slidesToShow: 4,
      slidesToScroll: 1,
      asNavFor: '.slider-for',
      dots: true,
      centerMode: false,
      focusOnSelect: true,
      dots: false,  
      arrows: false
  });

    // Slider for Tab 2
    $('.slider-for2').slick({
      slidesToShow: 1,
      slidesToScroll: 1,
      arrows: false,
      fade: true,
      asNavFor: '.slider-nav2'
  });
  $('.slider-nav2').slick({
      slidesToShow: 4,
      slidesToScroll: 1,
      asNavFor: '.slider-for2',
      dots: true,
      centerMode: false,
      focusOnSelect: true,
      dots: false,  
      arrows: false
  });
})

Answer №1

To ensure that the slick is properly attached to an event after the tab is shown, you need to make sure that the element exists at that point. The appropriate event for this scenario is shown.bs.tab. Below is a sample setup to demonstrate this concept. While it may not cover all scenarios, it serves its purpose.

var did_init_tab_2 = false;

const tabEl = document.querySelector('[data-bs-target="#tab_2"]');
tabEl.addEventListener('shown.bs.tab', event => {
  if (did_init_tab_2) {
    return;
  }
  did_init_tab_2 = true;
  $('.slider-for2').slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: false,
    fade: true,
  });
})



$(document).ready(function() {
  $('.slider-for').slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: false,
    fade: true,
  });


})
*,
*::before,
*::after {
  box-sizing: border-box;
}

img {
  max-width: 100%;
  height: auto;
  display: block;
}

.solution_nav .nav-link {
  border: none;
  background: none;
  cursor: pointer;
  position: relative;
  color: #ddd;
  padding: 16px 40px;
}

.solution_nav .nav-link.active {
  color: #343434;
  border-bottom: 1px solid #343434;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdafa2a2b9beb9bfacbd8df8e3ffe3fd">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c2e2323383f383e2d3c0c79627e627c">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js" integrity="sha512-XtmMtDEcNz2j7ekrtHvOVR4iwwaD6o/FUJe6+Zq+HgcCsk3kj4uSQQR8weQ2QVj1o0Pk6PwYLohm206ZzNfubg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" integrity="sha512-yHknP1/AwR+yx26cB1y0cjvQUMvEa2PFzt1c9LlS4pRQ5NOTZFWbhBig+X9G9eYW/8m0/4OXNx8pxJ6z57x0dw==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<div class="container mt-5">
  <div class="row justify-content-center">
    <div class="col-8">
      <ul class="nav solution_nav mb-5">
        <li class="nav-item">
          <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab_1" type="button" role="tab" aria-selected="false">TAB 1</button>
        </li>
        <li class="nav-item">
          <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab_2" type="button" role="tab" aria-selected="false">TAB 2</button>
        </li>

      </ul>
      <div class="tab-content">
        <div class="tab-pane fade show active" id="tab_1" role="tabpanel">

          <div class="slider slider-for">
            <img src='...' alt=''>
            <img src='...' alt=''>
            <img src='...' alt=''>
            <img src='...' alt=''>
          </div>


        </div>
        <div class="tab-pane fade" id="tab_2" role="tabpanel">

          <div class="slider slider-for2">
            <img src='...' alt=''>
            <img src='...' alt=''>

          </div>

        </div>
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing deployJava.runApplet for precise element targeting

After years of successfully maintaining an applet that utilizes the traditional: <script src="foo.js"></script> method for embedding a Java applet, we can no longer ignore the need for change. It's time to switch to: deployJava.runAppl ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...

Send a substantial item for display using Express Layout

Utilizing Express layouts to render my webpage upon accessing a specific route: The current project I am developing is an admin panel designed for editing a substantial table of data (imagine a website dedicated to managing thousands of product entries, fo ...

Identify compatibility with the background-attachment property set to fixed

I've been searching for an updated answer on this topic, but I couldn't find one so I wanted to confirm. My goal is to achieve a parallax effect using background-attachment: fixed, however I've noticed that it doesn't work on mobile ph ...

Sharing the state of a button group across different tabs using Bootstrap 5 and JQuery (or pure JavaScript): A complete guide!

Creating a tabbed web page using Bootstrap 5 nav-tabs for the front end and JQuery for the back end. I aim to have a single radio button group displayed on all tabs, with the state of the group persisting across tab changes. Currently, both tabs display t ...

Promise chain failure in express

I've developed an express.js server for managing REST API requests and extracting data from a MongoDB database. However, I'm encountering an issue with the promise chain when I send a GET request to a specific endpoint ("localhost:8081/api/getUse ...

Stop Antd Modal from automatically scrolling to the top

At the moment, I'm utilizing Ant Design (v4.22.8) and Next.js (v12.3.4) in my project. One issue I've encountered is with a Modal component that activates when a button is clicked. Instead of overlaying the current content on the screen, the moda ...

Accessing specific elements within multi-dimensional arrays using JavaScript

I've embarked on the exciting journey of creating my own 'Choose Your Adventure!' game, but I've hit a snag. I'm struggling to effectively target specific values within the multi-dimensional array I constructed. In order to add som ...

Tips for restricting the size of uploaded files or the quantity of files in multer express and effectively managing any errors

I am currently working on a code that requires me to set limits on file size or the number of files that can be uploaded. For instance, I want to restrict users from uploading more than 100 files at once or limit the total upload size to 100 mb. However, ...

Removing   from a text node using JavaScript DOM

I am currently working with xhtml in javascript. To retrieve the text content of a div node, I am concatenating the nodeValue from all child nodes where nodeType is Node.TEXT_NODE. However, sometimes the resulting string includes a non-breaking space enti ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

Why does the getComputedStyle function return null for IE11 and Edge when using Kendo React Grid within a Popout window, while it works fine in Chrome, Opera, and Firefox?

Check out my stackblitz demo where I am experimenting with rendering a Kendo React Grid inside a popout window using the react-popout-component. The demo runs smoothly in Chrome, Opera, and Firefox, but encounters issues in Edge and IE11 due to a null valu ...

Experiencing difficulties with arrays in JavaScript while using React Native

Programming Challenge let allURL = [] const [toReadURL, setToReadURL] = useState([]) useEffect(() => { const listReference = sReference(storage, parameterKey) // Retrieve all the prefixes and items. listAll(listReference) .then((res ...

Working with Variables in JavaScript and PHP Scripting Languages

I have a PHP script that displays all the folders (categories) on my website: echo "<ul>"; foreach(glob('category/*', GLOB_ONLYDIR) as $dir) { $dir = str_replace('category/', '', $dir); echo '& ...

The default props defined in the React component's child element are taking precedence over the custom props supplied by the parent component

The font size is being displayed as 20 and the color as 'red', instead of the font size being 12 and the color being 'blue' as specified in the parent component. However, the fontWeight as 'bold' is showing correctly. I have ...

Tips for displaying the most recent data in Vue following a successful fetch operation

I have the following script to load data from the server after the page loads: <script> export default { data() { return { imageDirectory: "../../images/", fileName: "img", ...

Upcoming JWT authentication module

I've been working on a simple application using next.js and integrating JWT for user authentication. My goal is to have a single navbar and layout that can dynamically adjust based on the authentication status. Below is my code: import React from "r ...

What is the process for running a script during partial view rendering?

My view is strongly typed to a CalculateModel where a user inputs information and then makes an ajax post to the controller. The controller performs calculations using this data and returns a PartialView strongly typed to the ResultCalculateModel. The Res ...

Using w3-include-html with a relative URL path

Is there a way for me to use the same header HTML on multiple pages within subdirectories without having to duplicate the file itself? As shown in the code snippet below, the header file is located in both the current directory and parent directory. While ...

Notify the ajax success if the returned data is null

Is there a way to display an alert message in the AJAX return request if no data is present? I have attempted this in the AJAX success function, but it seems to not be working! This is my current script: <script> $(document).ready(function () ...