Auto-switching Bricks Tabs

Looking to implement an auto-play/rotate feature for the Bricks‘ Tabs (Nestable) element where the tabs switch every x seconds when the element is scrolled into view?

Here’s the code for that, thanks to ChatGPT.

First, select the Tabs (Nestable) element, go to STYLE → CSS and paste this in the ‘CSS classes’ field: autoplaying-tabs

Then click on the Settings gear icon at the top → PAGE SETTINGS → CUSTOM CODE and paste this in Body (footer) scripts:

<script>
        document.addEventListener('DOMContentLoaded', function () {
            const tabsContainer = document.querySelector('.autoplaying-tabs');
            const tabTitles = tabsContainer.querySelectorAll('.autoplaying-tabs .tab-title');
            const tabPanes = tabsContainer.querySelectorAll('.autoplaying-tabs .tab-pane');
            let activeIndex = 0;
            let autoPlayInterval;

            // Helper function to handle the activation of tabs
            function activateTab(index) {
                tabTitles.forEach((title, i) => {
                    if (i === index) {
                        title.classList.add('brx-open');
                    } else {
                        title.classList.remove('brx-open');
                    }
                });

                tabPanes.forEach((pane, i) => {
                    if (i === index) {
                        pane.classList.add('brx-open');
                    } else {
                        pane.classList.remove('brx-open');
                    }
                });
            }

            // Function to kick-start the auto-play
            function startAutoPlay() {
                autoPlayInterval = setInterval(() => {
                    activeIndex = (activeIndex + 1) % tabTitles.length;
                    activateTab(activeIndex);
                }, 3000); // Switch every 3 seconds
            }

            // Function to stop the auto-play
            function stopAutoPlay() {
                clearInterval(autoPlayInterval);
            }

            // Intersection observer to detect scrolling into view
            const observer = new IntersectionObserver(entries => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        console.log('Tabs container is in view. Starting Auto-Play.');
                        startAutoPlay();
                    } else {
                        console.log('Tabs container is out of view. Stopping Auto-Play.');
                        stopAutoPlay();
                    }
                });
            }, { threshold: 0.1 });

            observer.observe(tabsContainer);
        });
    </script>

Note: The code is only meant for the case of 1 Tabs (Nestable) element per page.

Instant access to 390+ Bricks code tutorials with BricksLabs Pro

Leave the first comment