Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading