Toggle autoplay on and off for components slider

Hi @Support-Luis,

I’ve created a slider on my page and I’d like to have a cta that toggles the autoplay setting of the slider when clicked.
I had tried with a slider that didn’t have autoplay set and it didn’t worked, figured it would need to be enabled first but it’s still not working.

I used a call back function to try get this working.
Could you have a look and see if you spotted something wrong?

Thanks!

<script>
// Autoplay toggle
window.fsComponents = window.fsComponents || [];
window.fsComponents.push([
  'slider',
  (sliderInstances) => {
    console.log('Slider Successfully loaded!');

    // Find the specific slider instance with class 'cx-audit_instance'
    const auditSlider = sliderInstances.find((sliderInstance) => 
      sliderInstance.el.classList.contains('cx-audit_instance')
    );

    if (auditSlider) {
      console.log('Found cx-audit_instance slider:', auditSlider);

      // Initial autoplay state
      let isPlaying = false;

      // Get the toggle button from the UI
      const toggleButton = document.getElementById('toggle-autoplay');

      if (!toggleButton) {
        console.error('Toggle button with ID "toggle-autoplay" not found!');
        return;
      }

      console.log('Toggle button found:', toggleButton);

      // Add click event listener to toggle autoplay
      toggleButton.addEventListener('click', () => {
        console.log(`Autoplay state before toggle: ${isPlaying ? 'Playing' : 'Paused'}`);

        if (isPlaying) {
          console.log('Stopping autoplay...');
          auditSlider.autoplay.stop();
        } else {
          console.log('Starting autoplay...');
          auditSlider.autoplay.start();
        }

        // Toggle the state
        isPlaying = !isPlaying;

        console.log(`Autoplay state after toggle: ${isPlaying ? 'Playing' : 'Paused'}`);
      });
    } else {
      console.error('No cx-audit_instance slider found.');
    }
  },
]);
</script>

Hey @joseph.bongrand!

I believe you are almost there! I think you are only missing updating the slider after stopping or starting the autoplay…

if (isPlaying) {
  console.log('Stopping autoplay...');
  auditSlider.autoplay.stop();
  auditSlider.update();
} else {
  console.log('Starting autoplay...');
  auditSlider.autoplay.start();
  auditSlider.update();
}

should do the trick. However please share a link if the issue persists!

1 Like

Hi @Support-Luis thanks for the help, I’ll give that a go and get back to you!

Needed a little bit of tweaking but this worked:

// Autoplay toggle
window.fsComponents = window.fsComponents || [];
window.fsComponents.push([
  'slider',
  (sliderInstances) => {
    console.log('Slider Successfully loaded!');

    // Helper function to find slider instance with retry
    function waitForSliderInstance() {
      console.log('Checking for Swiper instances...');

      const auditSlider = sliderInstances.find((sliderInstance) => {
        const rootElement = sliderInstance.el;
        return (
          rootElement.classList.contains('cx--audit_instance') ||
          rootElement.closest('.cx--audit_instance')
        );
      });

      if (auditSlider) {
        console.log('Found cx--audit_instance slider:', auditSlider);

        // Set autoplay parameters
        auditSlider.params.autoplay = {
          delay: 5000,                // Slide every 5 seconds
          disableOnInteraction: true, // Stop autoplay on user interaction
        };
        auditSlider.params.loop = false; // No looping
        auditSlider.autoplay.stop(); // Start with autoplay disabled

        console.log('Autoplay configured and disabled on load.');

        // Toggle autoplay logic
        const toggleButton = document.getElementById('toggle-autoplay');
        if (!toggleButton) {
          console.error('Toggle button with ID "toggle-autoplay" not found!');
          return;
        }

        let isPlaying = false;
        toggleButton.addEventListener('click', () => {
          console.log(
            `Autoplay state before toggle: ${isPlaying ? 'Playing' : 'Paused'}`
          );
          if (isPlaying) {
            auditSlider.autoplay.stop();
            console.log('Autoplay stopped.');
          } else {
            auditSlider.autoplay.start();
            console.log('Autoplay started.');
          }
          isPlaying = !isPlaying;
          console.log(
            `Autoplay state after toggle: ${isPlaying ? 'Playing' : 'Paused'}`
          );
        });

        // Stop autoplay on the last slide
        auditSlider.on('slideChange', () => {
          if (auditSlider.activeIndex === auditSlider.slides.length - 1) {
            console.log('Reached the last slide. Stopping autoplay.');
            auditSlider.autoplay.stop();
            isPlaying = false;
          }
        });
      } else {
        console.log('No slider with class "cx--audit_instance" found. Retrying...');
        setTimeout(waitForSliderInstance, 100); // Retry after 100ms
      }
    }

    // Start checking for the slider instance
    waitForSliderInstance();
  },
]);

The main issue I was encountering is that the slider instance wasn’t found because it seems my script was loading before

Thanks for sharing @joseph.bongrand!

I’m glad you’ve got this working :muscle: