title: Programmatically fade elements in JavaScript
body: <p>I'm working on a the script of the century which creates and deletes elements in set intervals, but I need to fade the elements first before deleting them. I'd like for this effect to be done programmatically and with JavaScript only.</p>
  
  <p>I tried to add fade out animations like so:</p>
  
  <pre><code>function createRandomDiv () {
    ...
    randomDiv.style.opacity = "1";
    randomDiv.style.transition = "opacity 0.1s ease-out";
    ...
  }
  </code></pre>
  
  <p>Then listen to the 'animationend' event to delete it, but it doesn't seen to be fading out.</p>
  
  <pre><code>function deleteRandomDiv () {
    ...
    div.style.opacity = "0";
    div.addEventListener('animationend', function () {
      this.remove();
    });
    ...
  }
  </code></pre>
  
  <p>Here is a bin of what I have so far: <a href="https://jsbin.com/nuqeyutopu/edit" rel="nofollow noreferrer">https://jsbin.com/nuqeyutopu/edit</a>?</p>
  
  <p>What I had:
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>console.clear();
  document.body.style.position = "fixed";
  document.body.style.height = "100%";
  document.body.style.width = "100%";
  document.body.style.backgroundColor = "#EFEFEF";
  
  var numDivs = 20;
  var maxSize = 400;
  
  function createRandomDiv() {
      var randomDiv = document.createElement("div");
      var size = Math.floor(Math.random() * maxSize) + "px";
      randomDiv.style.height = size;
      randomDiv.style.width = size;
      randomDiv.style.backgroundColor = getRandomColor();
      randomDiv.style.position = "absolute";
      randomDiv.style.top = getRandomPosition();
      randomDiv.style.left = getRandomPosition();
      randomDiv.style.display = "block";
      randomDiv.style.borderRadius = "500px";
      randomDiv.innerHTML = "&amp;nbsp";
      randomDiv.style.backgroundImage = "url(http://vignette2.wikia.nocookie.net/filthy-frank/images/8/8d/516c32f08e03d.png/revision/latest?cb=20151019010624)";
      randomDiv.style.backgroundSize="contain";
      document.body.appendChild(randomDiv);
  }
  
  function createDivs() {
    for(var i = 0; i &lt; numDivs; i++) {
      createRandomDiv();
    }
  }
  
  function getRandomPosition() {
    return Math.floor(Math.random() * 100) + "%";
  }
  
  function getRandomColor() {
      var letters = '0123456789ABCDEF';
      var color = '#';
      for (var i = 0; i &lt; 6; i++ ) {
          color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
  }
  
  function deleteRandomDiv() {
    var divs = document.querySelectorAll('div');
    divs[Math.floor(Math.random() * divs.length)].remove();
  }
  
  createDivs();
  
  setInterval(function () {
    createRandomDiv();
    deleteRandomDiv();
  }, 50);</code></pre>
  </div>
  </div>
  </p>