Zsolt
Zsolt

Reputation: 29

Why doesn't style.display take affect for me?

I'm trying to make a progress indicator and an error message. Initially I set the style="display: none;" attributes. I would like to change it to style="display: block;" with JS, but my code does not take affect. Could you please help what am I missing?

HTML part:

<div class="loader" id="loading-indicator" style="display: none;"></div>
    <div class="error-message" id="error-message" style="display: none;">
        An error has occured
    </div>

JS part:

export const initForm = () =>{
    const displayLoadingIndicator = document.getElementById('loading-indicator');
    const errorMessage = document.getElementById('error-message')
    document.getElementById('submit-button').addEventListener('click', async eventObjeckt =>{
        const country = document.querySelector('#country-name').value;
        console.log("CHECKPOINT 4: submit button was pushed");
        console.log(`CHECKPOINT 3: ${country}`);
        eventObjeckt.preventDefault();
        // loadingIndicator START 
        displayLoadingIndicator.style.display = "block";
        console.log("After setting displayLoadingIndicator.style.display to 'block' : ", displayLoadingIndicator)
        try{
            getData(country)
        }catch(e){
            errorMessage.style.display = 'block';

        }
        displayLoadingIndicator.style.display = "none";
        console.log("After setting back to displayLoadingIndicator.style.display to 'none': ", displayLoadingIndicator)
        // loadingIndicator END
    })

I console.log-ed the HTML elements before and after the .style.display = 'block' commands, but they all look like this:

<div class="loader" id="loading-indicator" style="display: none;"></div>

so the .style.display = "block"; did not take effect.

Thank you

Upvotes: 0

Views: 477

Answers (1)

Quentin
Quentin

Reputation: 943823

JavaScript functions are blocking and console.log is lazy about evaluating objects.

You set it to block, then some JavaScript runs, then you set it back to none. In that time, there is no repaint of the display (because the JS blocks it) and by the time either console.log statement looks at the element it is back to none.

If getData(country) is a time consuming operation, consider farming it off to a Webworker, and setting block when the webworker messages the main process that it has finished doing the work. MDN has a tutorial on webworkers.

Upvotes: 1

Related Questions