Autoplay Toggle

You're browsing the documentation for v3

Introduction

Splide supports play/pause buttons for autoplay, but they are separated. This tutorial explains how to make them as a single toggle button.

HTML

First, provide the toggle button by HTML. The example below wraps the button with the <div> element for styling, but it's not required.

<div class="splide">
<div class="splide__track">
<ul class="splide__list">
...
</ul>
</div>
<div class="my-autoplay-controls">
<button class="my-toggle-button" type="button">Pause</button>
</div>
</div>
HTML

JavaScript

Next, create the Splide instance and grab the toggle button. The pauseOnHover and pauseOnFocus options must be false because they will conflict with the button functionality. For example, if you enable the pauseOnHover option, autoplay will be paused before you click the button.

var splide = new Splide( '.splide', {
autoplay : true,
rewind : true,
pauseOnHover: false,
pauseOnFocus: false,
} );
var toggleButton = splide.root.querySelector( '.my-toggle-button' );
JavaScript

When autoplay begins, the button label should turn into "Pause", and vise versa. You can update it by listening to autoplay:play and autoplay:pause events.

var toggleButton = splide.root.querySelector( '.my-toggle-button' );
splide.on( 'autoplay:play', function () {
toggleButton.setAttribute( 'aria-label', 'Pause autoplay' );
toggleButton.textContent = 'Pause';
} );
splide.on( 'autoplay:pause', function () {
toggleButton.setAttribute( 'aria-label', 'Start autoplay' );
toggleButton.textContent = 'Play';
} );
JavaScript

Finally, we need to toggle autoplay when the user clicks the button. The Autoplay component provides some methods to control it:

toggleButton.addEventListener( 'click', function () {
var Autoplay = splide.Components.Autoplay;
if ( Autoplay.isPaused() ) {
Autoplay.play();
} else {
Autoplay.pause();
}
} );
JavaScript

Done! Now we get the slider like the example above.

Tips

If you'd like to keep pauseOnHover and pauseOnFocus options, move the toggle button out of the slider:

<div class="splide">
<div class="splide__track">
<ul class="splide__list">
...
</ul>
</div>
</div>
<div class="my-autoplay-controls">
<button class="my-toggle-button" type="button">Pause</button>
</div>
HTML