Skip to content

Instantly share code, notes, and snippets.

@quietcactus
Created May 17, 2024 17:51
Show Gist options
  • Select an option

  • Save quietcactus/dd4cd518d671dcf88d8751b0c51a7ded to your computer and use it in GitHub Desktop.

Select an option

Save quietcactus/dd4cd518d671dcf88d8751b0c51a7ded to your computer and use it in GitHub Desktop.
Swiper - Custom Pause / Play Button
.play-pause-btn {
position: absolute;
bottom: 15px;
right: 15px;
width: 25px;
height: 25px;
display: -webkit-flex;
display: -moz-flex;
display: -o-flex;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.8rem;
background: none;
border: 1px solid var(--color-black);
color: var(--color-black);
opacity: 0.8;
padding: 5px;
outline: black;
transition: background-color 0.3s ease-in-out, color 0.3s ease-in-out;
}
.play-pause-btn:active {
transform: none;
}
.play-pause-btn:hover,
.play-pause-btn:focus {
background: var(--color-black);
color: var(--color-white);
}
<button class="play-pause-btn" aria-label="Play/Pause"><i class="fa-solid fa-pause"></i></button>
document.addEventListener('DOMContentLoaded', (event) => {
// Initialize all Swiper instances on the page
document.querySelectorAll('.swiper').forEach((el) => {
new Swiper(el, {
// Your Swiper options here
// Make sure to include 'autoplay' if you haven't already
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
});
// Set a custom property to track play/pause state
el.swiper.autoplay.paused = false;
});
// Add click event listener to all play-pause buttons
document.querySelectorAll('.play-pause-btn').forEach((button) => {
button.addEventListener('click', function () {
// Find the closest Swiper container
var swiperContainer = this.closest('.swiper');
// Access the Swiper instance
var swiperInstance = swiperContainer.swiper;
// Check if autoplay is currently paused
if (swiperInstance.autoplay.paused) {
// If paused, start autoplay
swiperInstance.autoplay.start();
swiperInstance.autoplay.paused = false;
// Change icon to 'pause'
icon.classList.remove('fa-play');
icon.classList.add('fa-pause');
} else {
// If playing, stop autoplay
swiperInstance.autoplay.stop();
swiperInstance.autoplay.paused = true;
// Change icon to 'play'
icon.classList.remove('fa-pause');
icon.classList.add('fa-play');
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment