Giovanni5454
Giovanni5454

Reputation: 31

css transitions don't work when changes are made in javascript

#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?

Upvotes: 2

Views: 82

Answers (1)

tenshi
tenshi

Reputation: 26307

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>

Upvotes: 2

Related Questions