Closed nickpish closed 2 years ago
Thank you - glad you like it!
That should be fairly simple - the entire slider is markup only, so you can implement your design using responsive rules.
Related to loading - you can call swiffyslider.init()
manually at any event to initialize all slider instances - or you can use swiffyslider.initSlider(element)
to initialize a specific instance.
The example below will not load any sliders from the start - but when the viewport comes under 500px, either on load or on resize, the script will download the esm version of Swiffy and initialize one specific instance of the slider:
<script>
// Create a match Function
function startSlider(mediaMatches) {
if (mediaMatches.matches) {
import ('https://cdn.jsdelivr.net/npm/swiffy-slider@1.5.3/dist/js/swiffy-slider.esm.min.js').then((swiffysliderModule) => {
window.swiffyslider = swiffysliderModule.swiffyslider;
window.swiffyslider.initSlider(document.getElementById("mySlider"));
});
}
}
window.addEventListener('DOMContentLoaded', () => {
// Create a media watcher
const watchViewport = window.matchMedia("(max-width: 500px)");
// Call the slider watcher function when page loads:
startSlider(watchViewport);
// Listen for viewport changes:
watchViewport.addListener(startSlider);
}
</script>
<div class="swiffy-slider" id="mySlider">
...
</div>
If you have more than one slider on the same page that becomes visible in smaller viewport, you can initialize all of them using window.swiffyslider.init()
instead.
If you want to include the script in the header, you can do that without automatic initializing using data-noinit attribute:
<script src="https://cdn.jsdelivr.net/npm/swiffy-slider@1.5.3/dist/js/swiffy-slider.min.js" data-noinit defer>
If you want to include the script in your build script, you can include it without calling the initializer - and let the watcher do the initialization:
// import Swiffy Slider JS
import { swiffyslider } from 'swiffy-slider'
window.swiffyslider = swiffyslider;
// import Swiffy Slider CSS
import "swiffy-slider/css"
function startSlider(mediaMatches) {
if (mediaMatches.matches) {
window.swiffyslider.initSlider(document.getElementById("mySlider"));
});
}
}
Hope this answers your question.
Wow, thanks so much @nicped for the extremely detailed and helpful response! I'll give this a shot- thanks again!
First off, thank you for building such a fantastic slider/carousel! I have a unique project the layout for which requires a slider to initialize on card-style elements only for smaller viewports, and I'm wondering if you have a recommended method for initializing/de-initializing Swiffy via a
resize
event, say, withwindow.matchMedia
or some other method? Thanks for any suggestions here!