2

#loading_screen {
  display: none;
  z-index: 1;
  height: 100vh;
  width: 100vw;
  opacity: 0;
  background-color: red;
  transition: opacity 4s 0s ease;
}
<div id="loading_screen" class="page">
</div>

<script>
  function hide_page() {
    const loading = document.getElementById('loading_screen');

    loading.style.display = 'block';
    loading.style.opacity = '1';
  }
  hide_page()
</script>

The loading_screen div appears instantly, as if the transition didn't even exist

Is there a chance that the css is not functional immediately when I run the page?

1 Answer 1

2

You need to wait for the browser to update and paint the loading element first, then you can use setTimeout to change the opacity after the browser has done its paint.

function hide_page() {
  const loading = document.getElementById('loading_screen');

  loading.style.display = 'block';
  setTimeout(() => {
    loading.style.opacity = '1';
  });
}

hide_page();
#loading_screen {
  display: none;
  z-index: 1;
  height: 100vh;
  width: 100vw;
  opacity: 0;
  background-color: red;
  transition: opacity 4s ease;
}
<div id="loading_screen" class="page">
</div>

Sign up to request clarification or add additional context in comments.

6 Comments

You're missing the second argument to setTimeout()
@Barmar The second argument is optional, no? It defaults to 0.
@caTS (I hope you see this message) The problem persists for me, although before I got your help, the transition didn't work at all, now after a while I noticed that it doesn't always work, I don't change anything in the code, I just refresh the page and the transition sometimes doesn't work. It's really annoying, do you have any idea what to do to be 100% sure that the transition will always trigger?does it have to do with requestAnimationFrame()? do you know if this method can work in my case?
@Giovanni5454 It probably will, but without a way to reproduce the problem, I can't say for sure. Might be worth asking another question for...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.