title: JavaScript/CSS: Delay between adding element to DOM and its CSS rules being applied?
body: <p>I am using JavaScript to dynamically add an element to the DOM. I want to use CSS3 transitions to "fade in" the element as it is added.</p>
  
  <p>I am using something like the following to achieve this:</p>
  
  <pre><code>function add(el) {
  
      el.className += ' fader';
      el.style.opacity = 0;
  
      document.getElementById('parent-element').appendChild(el);
      //setTimeout(function () { el.style.opacity = 1; }, 5);
      el.style.opacity = 1;
  
  }
  </code></pre>
  
  <p>And the CSS:</p>
  
  <pre><code>.fader {
      -webkit-transition: opacity 0.5s;
  }
  </code></pre>
  
  <p>This does not work as expected - the element does not fade in. If I replace the line <code>el.style.opacity = 1;</code> with <code>setTimeout(function () { el.style.opacity = 1; }, 5);</code>, as seen commented-out above, it <em>does</em> work as expected.</p>
  
  <p>I am guessing that the first case does not work as there is some delay between adding the element and the appropriate CSS rules being applied to it. The 5ms delay created by the <code>setTimeout</code> in the second case gives enough time for these rules to be applied, therefore the fade takes place as expected.</p>
  
  <p>Firstly, is this a correct assumption? Secondly, is there a better way to solve this? The <code>setTimout</code> feels like a hack. Is there perhaps some event that is fired once the element has had all its styles applied?</p>