numerous instances of Splide sliders

I am navigating this website and using Splide.js for the first time. Although I have a basic understanding, I lack experience in this area. My goal is to incorporate multiple slides on my webpage while keeping the main slide active at all times.

To achieve this, I am setting up two sliders:

document.addEventListener( 'DOMContentLoaded', function () {
    mainslide = new Splide( '#mainslide', {
        type   : 'loop',
        perPage: 5,
        perMove: 1,
        direction: 'rtl',
        trimSpace: false,
        keyboard: true,
        gap: '1em',
        width: '100%',
        height: '100%',
    })
    wheelslide = new Splide( '#wheelslide', {
        type: 'loop',
        perPage: 5,
        perMove: 1,
        direction: 'rtl',
        trimSpace: false,
        keyboard: true,
        gap: '1em',
        width: '100%',
        height: '100%'
    })
} );

Upon loading my page, I execute:

mainslide.mount();

When transitioning to a different page where I want to showcase another slider, I perform the following actions:

$('#mainslide').hide()
mainslide.destroy(true)
mainslide.mount();
$('#wheelslide').show()

The issue arises when the new page or slider still references the original slider. It seems like the initial slider is not being destroyed properly. Upon checking the id through console.log, it displays mainslide01 instead of wheelslide01. I find myself at an impasse and uncertain about how to proceed further.

Thank you for your assistance.

Answer №1

I encountered a similar issue but managed to find a solution. Take a look at the code snippet provided below:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="assets/css/splide-core.min.css">
  <script src="assets/js/splide.min.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      new Splide('#new-product', {
        perPage: 3,
        perMove: 1,
        gap: "30px",
        pagination: false,
      }).mount();
    });
    
    document.addEventListener('DOMContentLoaded', function () {
      new Splide('#featured-product', {
        perPage: 4,
        perMove: 1,
        gap: "30px",
        pagination: false,
      }).mount();
    });
  </script>
  <title>SplideJS</title>
</head>
<body>

<div id="new-product" class="splide">
    <div class="splide__track">
        <ul class="splide__list">
            <li class="splide__slide">Slide 01</li>
            <li class="splide__slide">Slide 02</li>
            <li class="splide__slide">Slide 03</li>
            <li class="splide__slide">Slide 04</li>
            <li class="splide__slide">Slide 05</li>
        </ul>
    </div>
</div>

<div id="featured-product" class="splide">
    <div class="splide__track">
        <ul class="splide__list">
            <li class="splide__slide">Slide 01</li>
            <li class="splide__slide">Slide 02</li>
            <li class="splide__slide">Slide 03</li>
            <li class="splide__slide">Slide 04</li>
            <li class="splide__slide">Slide 05</li>
            <li class="splide__slide">Slide 06</li>
      <li class="splide__slide">Slide 07</li>
        </ul>
    </div>
</div>

</body>
</html>

To make sure both sliders work independently on the same page, remember to assign an id attribute to the main slider containers and reference them in the Splide initialization code as shown above.

Answer №2

For efficient management of multiple slider instances, I suggest utilizing the built-in 'data-splide' attribute for a slider-specific configuration.

  1. To begin, construct your splide.js HTML markup as you normally would
  2. Insert your slider options within the predefined "data-splide" attribute, like so:

<div class="splide" data-splide='{"type":"loop","perPage":3, "arrows":false, "pagination":false, "heightRatio":0.25 }'>

Refer to the official documentation:

  1. Subsequently, execute a rather generic function for initializing/mounting all slider instances

var splides = document.querySelectorAll('.splide');
// 1. Are there any splide elements?
if(splides.length){
    // 2. Process all instances
    for(var i=0; i<splides.length; i++){
        var splideElement = splides[i];
        //3.1 Take default options if none specified by 'data-splide' attribute
        var splideDefaultOptions = 
        {
            type   : 'slide',
            rewind: true,
            perPage: 1,
            autoplay:false,
            arrows:true,
            pagination:true,
            drag:true,
            keyboard:true,
            heightRatio: 0.5,
            cover: true,
        }
        
        //3.2 Override default options if specified by 'data-splide' attribute
        var splide = new Splide( splideElement, splideDefaultOptions ); 
        // 3. Mount/initialize this slider
        splide.mount();
    }
}
<link href="https://cdn.jsdelivr.net/npm/@splidejs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="354645595c515075061b041b">[email protected]</a>/dist/css/splide.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/@splidejs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f3f0ece9e4e5c0b3aeb1ae">[email protected]</a>/dist/js/splide.min.js"></script>


            <div class="splide">
              <div class="splide__track">
                <ul class="splide__list">
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/237/200/300" class="slider-img">
                  </li>
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/236/200/300" class="slider-img">
                  </li>
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/235/200/300" class="slider-img">
                  </li>
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/234/200/300" class="slider-img">
                  </li>
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/233/200/300" class="slider-img">
                  </li>
                </ul>
              </div>
            </div>
      
            <div class="splide" data-splide='{"type":"loop","perPage":3, "arrows":false, "pagination":false, "heightRatio":0.25 }'>
              <div class="splide__track">
                <ul class="splide__list">
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/237/200/300" class="slider-img">
                  </li>
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/236/200/300" class="slider-img">
                  </li>
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/235/200/300" class="slider-img">
                  </li>
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/234/200/300" class="slider-img">
                  </li>
                  <li class="splide__slide">
                    <img src="https://picsum.photos/id/233/200/300" class="slider-img">
                  </li>
                </ul>
              </div>
            </div>

Potential pitfalls: Ensure that your data attribute is enclosed in single quotes when specifying a JSON string with object keys in double quotes, like so: data-splide='...'

The primary advantage:
You only require one general mounting function that can be saved in an external JavaScript file and included on any page (after loading splide.js), for example:

<script src="..splide.min.js"></script>
<script src="..splide-init.js"></script>

You may also merge/concatenate your splide.js core file with the initialization script and load it asynchronously to minimize rendering delays:

<script src="..splide.combined.js" defer></script>

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

What is the best way to pass route props using the <router-link> component?

Check out the button below that links to a specific route: <router-link class="q-pa-md" :to="{ name: 'Edit'}" id="item.id"> <q-btn outline>Edit</q-btn> </router-link> Take a look at my router se ...

Sort out online notifications using client-side technology

When a notification is sent to a specific topic, such as... const message = { data: { cost: 49 }, topic: 'apple' } admin.messaging().send(message) The question revolves around controlling/filtering notifications based on user-defined criter ...

Is it permissible to enclose useEffect hooks within an IIFE?

Currently, I am dealing with a project that is rife with anti-patterns. One issue that has caught my attention is the use of Immediately Invoked Function Expressions (IIFE) around multiple useEffect hooks. Here is a snippet of the code in question: conditi ...

"What is the best way to add content to the end of the last child element using Angular's

Currently, I am facing an issue with appending a button after an input field using an Angular7 directive. The problem lies in the fact that the Renderer2 method appendChild is placing the button before the input field. Button appearing before the input fi ...

What is the best location to store the JWT bearer token?

Exploring options for storing JWT tokens in a Bearer header token for my application. Looking for the most efficient storage mechanism. Would love some insight on how to accomplish this using jQuery. Any recommendations for a secure method? ...

I'm having trouble locating the airtable module, even after I successfully ran npm install airtable

Currently attempting to integrate the airtable api into my website's backend using node.js. However, upon writing var Airtable = require('airtable'); and running the file with node [filepath], I encounter an error in the command prompt: ...

What is the solution for the error "Unable to render a <Router> within another <Router>"?

Recently delving into the realm of React, I have embarked on a journey to build a small application. After successfully constructing the backend RestApi, I turned my attention to crafting the frontend using React with the following code snippet: App.js: i ...

Conceal the button once the page has been converted to an HTML format

Located at the bottom of the HTML page is a button that triggers an onClick function. Since the page only contains internal CSS, when users save the page (by right-clicking and selecting Save As) as an HTML file, it is saved without any additional folders ...

The CE button on the calculator seems to be malfunctioning

My calculator's CE button isn't working as expected – instead of deleting the last entered number, it clears all numbers. I want the CE button to only delete the last number entered. Additionally, I want the calculator to display a default valu ...

The JavaScript window variable is not being returned from an AJAX request without a delay

At the beginning of my script, I set a default value for the name of a kmz file that I need for Google Maps. This value is stored in a window variable. window.kmz="Delaware_River_Basin.kmz" After running an ajax request, I receive the correct value for t ...

How can a pop-up be positioned to appear in the right bottom corner using jQuery

Is there a way to position a pop-up at the bottom right corner of the window? I have code that centers the pop-up in the window, but I'm looking to place it specifically at the bottom right corner. $(id).css('top', winH - $(id).height()); ...

The issue code R10, indicating a boot timeout, has arisen as the web process failed to connect to $PORT within 60 seconds of initiating on Heroku platform

After deploying my Node.js WebApp to Heroku, I encountered the following error: 2021-06-01T09:19:42.615419+00:00 heroku[web.1]: State changed from crashed to starting 2021-06-01T09:19:47.259832+00:00 heroku[web.1]: Starting process with command `node app.j ...

Is there a way to modify the fundamental characteristics of a Geometry within Three.js? Such as adjusting the radius, number of vertices, and other parameters?

My task involves creating a tetrahedron with a radius of 3 // create a tetrahedron var tetGeometry = new THREE.TetrahedronGeometry(3); var tetMaterial = new THREE.MeshLambertMaterial( {color: 0x20f020, transparent:true, opacity:0.6}); ...

An error has occurred while trying to declare Symbol InputText during an Angular production build

Currently, I am facing an issue while trying to export the primeng modules from a file. During the test build, I do not encounter any errors. However, when I proceed with the production build, I come across the following error: ERROR in Symbol InputText de ...

Guide to adding animation to the Bootstrap 4 Dropmenu

There is a collapse animation on the navbar toggler: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-sca ...

Unlock the Table Value

I am having trouble retrieving the value for <td> Value3 How can I navigate through this DOM to extract the value from <td>? <table> <thead> <tr> <th col="value2"></th> </tr> </thead&g ...

Encountered a connection error in the Spring Boot application: net::ERR_CONNECTION_REF

Currently working on a school project developing a Spring Boot application using Restful. The application runs smoothly locally, but when deployed to AWS, I am encountering an "net::ERR_CONNECTION_REFUSED" error for all my GET and POST requests sent to the ...

Discord bot that combines the power of discord.js and node.js to enhance your music

I am currently working on a Discord bot designed to play music in voice chat rooms. However, I am facing some issues with properties. Whenever I try to launch the bot using "node main", I encounter the following error message: "TypeError: Cannot read prope ...

Unable to execute redirect function in Next.js 14 application

I've been working on implementing basic authentication within a Next.js app, however I'm encountering issues with redirecting to the homepage from the auth.ts file. Below is a snippet of the code where I am implementing the loginForm: //loginForm ...

Generating a matrix of HTML video elements in p5.js triggers Uncaught TypeError

Struggling to create a 2D array of video objects. It works fine with a regular array, but throws an error when attempting to make it 2D - Uncaught TypeError: Cannot read property 'tv' of undefined. The problem seems to be in this line of code: tv ...