Opening Up A Specific Tab, Toggle, or Accordion Using Elementor

One of the nice things about WPBakery is that you can easily link to and open a specific tab out of the box.  Hopefully Elementor will add this feature in the future, but until they do, here’s some JS code to make it happen, using the tab, toggle, or accordion titles as the anchor links (so that you don’t have to hard-code anything – it just works).  Obviously you will need to enqueue what follows in a separate script, or otherwise include this on your page that has a tab, accordion, or toggle instance.

Note: I modified the original idea for this from https://element.how/elementor-open-specific-tab-toggle-accordion/.  I chose to deviate from the original code both to avoid hard-coding anchor names, as well as to use the same code snippet for tabs, toggles, and accordions, since I never know which of these elements content managers at the University may employ.

				
					(function ($) {

    // known limitation - won't work if different modules are mixed on page (eg, one tab and one accordion on the same page)
    document.addEventListener('DOMContentLoaded', function () {

        // fetch all the tab, accordion, and toggle titles
        let desktoptitles = $('.elementor-tab-desktop-title');
        let mobiletitles = $('.elementor-tab-mobile-title');

        // this check is needed for the tab module to work
        if (!$(desktoptitles).length) 
            desktoptitles = $('.elementor-tab-title');

        // iterate them
        $(desktoptitles).each(function (index, title) {

            // clean up the titles to remove all non-alphanumeric chars, and prepend with an anchor
            title = $(this).text().replace(/\W/g, '');
            title = '#' + title;

            // compare the hash with the tab title
            if (window.location.href.indexOf(title) > -1) { 
                
                setTimeout(function () {

                    // trigger a click on the tab title
                    desktoptitles.eq(index).click();
                    mobiletitles.eq(index).click();
                    
                    // scroll to the correct position on the page.  Feel free to adjust offset
                    $('html, body').animate({
                        scrollTop: desktoptitles.eq(index).offset().top - 250
                    }, 'slow');

                }, 1200);
                
            }

        });

        // also handle when users click other tabs (update links in the browser)
        $(desktoptitles).click(function (index, title) {

            var current_location = window.location.href;
            current_location = current_location.split("#");

            // clean up the titles to remove all non-alphanumeric chars, and prepend with an anchor
            title = $(this).text().replace(/\W/g, '');
            title = '#' + title;

            window.location = current_location[0] + title; 

        });

    });

})(jQuery);