Owen Sullivan
Owen Sullivan

Reputation: 143

How do I fade out a div using pure JavaScript?

I have the following code for a preloader on my site:

setTimeout(function() {
  document.getElementById("loader-wrapper").style.display = 'none';
}, 1250);
<div class="loader-wrapper" id="loader-wrapper">
  <div id="loading">
    <div class="loader"></div>
  </div>
</div>

Currently the div disappears after 1.25 seconds, but how do I make the loader-wrapper fade out after those 1.25 seconds (without using CSS or jQuery)?

Upvotes: 2

Views: 4209

Answers (3)

Penny Liu
Penny Liu

Reputation: 17388

Look into object.style.transition JavaScript syntax.

Here is a simplified running example of @Owen Sullivan's solution.

setTimeout(function() {
  var loader = document.getElementById("loader-wrapper");
  loader.style.transition = '.5s';
  loader.style.opacity = '0';
  loader.style.visibility = 'hidden';
}, 1250);
<div class="loader-wrapper" id="loader-wrapper">
  <div id="loading">
    <div class="loader">loader</div>
  </div>
</div>

Upvotes: 6

Owen Sullivan
Owen Sullivan

Reputation: 143

What ended up working for me:

<script>
  setTimeout(function() {
    var loader = document.getElementById("loader-wrapper");
    loader.style.WebkitTransition = 'visibility .5s, opacity .5s';
    loader.style.opacity = '0';
    loader.style.visibility = 'hidden';
  }, 1250);
</script>

This sets the visibility to hidden and allows all the content underneath the loader-wrapper div to be interacted with (in my case, buttons and forms).

Upvotes: 0

Sergii Rudenko
Sergii Rudenko

Reputation: 2684

You can do it with using of inline styles on the loader element:

<script>
  setTimeout(function() {
    var el = document.getElementById("loader-wrapper");
    // 1s - time of the animation duration
    // set transition property for webkit browsers only
    el.style.WebkitTransition = 'opacity 1s ease-in-out;'
    el.style.opacity = '0';
  }, 1250);
</script>

JSbin link.

To set transition for all browsers you need to set all transition properties. You can get if from this question.

For more information and animation examples check this question.

Upvotes: 1

Related Questions