When using the Splide library, you encounter a situation where you need multiple sliders on one page without any conflict. Here is how to do it.
Now with newer versions, it is better explained in the library documentation and users shouldn’t be confused. But it’s worth describing more.
Table of Contents
There are some ways to do that but I use the simplest one. Just do these three steps:
Include Splide Library CSS and JavaScript files
There are different ways to include them in your project. I prefer to include them via CDN. In this example, Splide v4.0.7 (the latest version now) will be included.
CSS should be included in between <head>
and </head>
of your HTML codes:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.0.7/dist/css/splide.min.css">
Add JavaScipt before </body>
of your HTML codes:
<script src="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.0.7/dist/js/splide.min.js"></script>
Add Splide Multiple Sliders on One Page (HTML)
You can grab one of its premade codes and include it in your project’s HTML file. The key is that you have to add an id
attribute to each slider’s code.
<!-- First slider codes -->
<section class="splide" id="first-slider">
<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>
</ul>
</div>
</section>
<!-- Second slider codes -->
<section class="splide" id="second-slider">
<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>
</ul>
</div>
</section>
Note that I wrote id="first-slider"
to the first slider’s code. And I wrote id="second-slider"
to the second one.
Apply Splide to Your Multiple Sliders via JavaScript
To do that, use a script tag like the one below. Consider adding these codes at the bottom of your HTML codes before </body>
:
<script>
new Splide("#first-slider").mount();
new Splide("#second-slider").mount();
</script>
In the script above, I used the id attribute values that were added before to the sliders’ HTML codes.
Here is the complete final result as a pen and I just added some custom CSS codes to show two sliders better:
See the Pen Multiple Splide Sliders on the Same Page by Alvand WordPress Themes (@alvand1399) on CodePen.
Conclusion
That’s it. I hope this post helped you in a way. Do you want to know how to use the CSS clamp() function for better responsiveness?
Leave a Reply