js isn't executing on first page load

68 Views Asked by At

I'm working with a WordPress site using the Divi theme. I have inserted a JavaScript code into the body via the theme options. However, I'm encountering an issue where the script doesn't executes until the second page load. Additionally, it doesn't seem to run at all when using Incognito mode. This script is intended to create interactive tooltips that respond to user actions, enhancing the user experience on the site.

window.onload = function() {
    function getTooltipContent(id) {
        let content = '';

        switch (id) {
            case 'Kreis1':
                // some text
                break;
            // Other cases
            default:
                content = ''; 
        }

        return content; 
    }

    const kreise = document.querySelectorAll('.svg-container g[id^="Kreis"]');
    const infoContainer = document.getElementById('info-container');
    const infoText = document.getElementById('info-text');
    const svgContainer = document.querySelector('.svg-container');

    kreise.forEach(kreis => {
        kreis.addEventListener('click', () => {
            const content = getTooltipContent(kreis.id);
            infoText.innerHTML = content; // Tooltip content is set here

            if (window.innerWidth <= 768) {
                infoContainer.classList.add('info-container-mobile-active');
            } else {
                infoContainer.classList.add('active');
                svgContainer.classList.add('active');
            }
        });
    });
}

I've tried using both the DOMContentLoaded event and the jQuery ready function to address this issue, but these approaches did not resolve the problem.

0

There are 0 best solutions below