Aleš Sýkora / May 3, 2024 / 0 comments

Bricks: Auto scroll to active Tab ─ Tabs Nestable element

Post summary: If you want your browser to autoscroll to the tab content when user click on Tab nestable title (especially in mobile view) you will need to add some javascript to your page. I use Code Block to add this code only where I need it. Here is the code to insert into Bricks Code Block:…

If you want your browser to autoscroll to the tab content when user click on Tab nestable title (especially in mobile view) you will need to add some javascript to your page. I use Code Block to add this code only where I need it.

Auto scroll to the active tab content

Here is the code to insert into Bricks Code Block:

<script>
document.addEventListener('DOMContentLoaded', function () {
    // select tab titles
    var tabTitles = document.querySelectorAll('.product_tabs__title');

    tabTitles.forEach(function(tab) {
        tab.addEventListener('click', function() {
            // timeout to get the right tab content with .brxe-open class
            setTimeout(() => {
                // find active tab content with .brx-open
                var activeTabContent = document.querySelector('.tab-content .tab-pane.brx-open');
                console.log('Active tab content:', activeTabContent); // check if it works in console

                if (activeTabContent) {
                    // scroll to content
                    activeTabContent.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                } else {
                    console.error('No active tab content found');
                }
            }, 300); // timeout before initialization
        });
    });
});
</script>

Add the offset to the top of scroll

If you need to add the offset to scroll, use this code instead:

document.addEventListener('DOMContentLoaded', function() {
    var tabTitles = document.querySelectorAll('.product_tabs__title');
    tabTitles.forEach(function(tab) {
        tab.addEventListener('click', function() {
            setTimeout(() => {
                var activeTabContent = document.querySelector('.tab-content .tab-pane.brx-open');
                if (activeTabContent) {
                    var top = activeTabContent.getBoundingClientRect().top + window.scrollY;
                    var offset = 50; // Set the offset in pixels from the element
                    window.scrollTo({
                        top: top - offset,
                        behavior: 'smooth'
                    });
                }
            }, 300);
        });
    });
});

Fuel my passion for writing with a beer🍺

Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻

0 comments

Share Your Thoughts