Why do I get null objects without a 2-second delay in JS?

Why do I get null objects without a 2-second delay in JS?

deemoss
New Member
4 0 0

Hi guys,

 

I get null objects, unless, I use a 2-second delay after the doc loads. I added the JS in assets and added to theme.liquid at the end:

 

 

{{ 'show-hide-bearings.js' | asset_url | script_tag}}
</body>

 

 

 Without this timeout, I get the "...does not exist" strings. How can I make this work without this arbitrary delay?

 

This is the code:

 

 

window.addEventListener('load', function() {
    setTimeout(() => {
            const hideButton = document.querySelector('#tda-customizer-customization-option-value-ane8cb');
            const steelButton = document.querySelector('#tda-customizer-customization-option-value-oumyu3');
            const ceramicButton = document.querySelector('#tda-customizer-customization-option-value-niaxf9');
            const showButton = document.querySelector('#tda-customizer-customization-option-value-c7loz');

            if (hideButton) {
                console.log('hideButton exists:', hideButton);
            } else {
                console.log('hideButton does not exist');
            }

            if (steelButton) {
                console.log('steelButton exists:', steelButton);
            } else {
                console.log('steelButton does not exist');
            }

            if (ceramicButton) {
                console.log('ceramicButton exists:', ceramicButton);
            } else {
                console.log('ceramicButton does not exist');
            }

            if (showButton) {
                console.log('showButton exists:', showButton);
            } else {
                console.log('showButton does not exist');
            } 
    }, 2000); // Delay of two seconds
});

 

 

Replies 0 (0)