Created
April 8, 2025 19:44
-
-
Save askwpgirl/9dfbd131331d425a056a6f5db3dde066 to your computer and use it in GitHub Desktop.
Add Pause Button to Elementor Carousels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Add this to Header/Footer plugin in the HTML <head> | |
<script> | |
document.addEventListener('DOMContentLoaded', function () { | |
const seen = new WeakSet(); | |
const interval = setInterval(() => { | |
const swiperEls = document.querySelectorAll('.swiper.swiper-initialized'); | |
swiperEls.forEach((swiperEl, index) => { | |
if (seen.has(swiperEl)) return; | |
const wrapper = swiperEl.querySelector('.swiper-wrapper'); | |
if (!wrapper || !swiperEl.swiper) return; | |
// Ensure ID | |
let wrapperId = wrapper.getAttribute('id'); | |
if (!wrapperId) { | |
wrapperId = 'swiper-wrapper-' + index; | |
wrapper.setAttribute('id', wrapperId); | |
} | |
// Avoid duplicate buttons | |
if (swiperEl.parentNode.querySelector('.pause-resume-button')) return; | |
const button = document.createElement('button'); | |
button.textContent = 'Pause'; | |
button.className = 'pause-resume-button'; | |
button.setAttribute('aria-controls', wrapperId); | |
button.setAttribute('aria-label', 'Pause Slider'); | |
button.setAttribute('aria-pressed', 'false'); | |
button.style.marginBottom = '10px'; | |
// Insert the button before the slider | |
swiperEl.parentNode.insertBefore(button, swiperEl); | |
// Toggle autoplay | |
button.addEventListener('click', function () { | |
const swiperInstance = swiperEl.swiper; | |
if (!swiperInstance) return; | |
if (this.textContent === 'Pause') { | |
swiperInstance.autoplay.stop(); | |
this.textContent = 'Resume'; | |
this.setAttribute('aria-pressed', 'true'); | |
} else { | |
swiperInstance.autoplay.start(); | |
this.textContent = 'Pause'; | |
this.setAttribute('aria-pressed', 'false'); | |
} | |
}); | |
// Mark this swiper as processed | |
seen.add(swiperEl); | |
}); | |
// Optional: stop polling after a while (e.g. after 10 seconds) | |
if (seen.size > 0 && seen.size === document.querySelectorAll('.swiper.swiper-initialized').length) { | |
clearInterval(interval); | |
} | |
}, 500); // check every 500ms | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment