title: Why is setTimeout needed when applying a class for my transition to take effect?
body: <p>I have an element with a transition applied to it. I want to control the transition by adding a class to the element which causes the transition to run. However, if I apply the class too quickly, the transition effect does not take place.</p>
  
  <p>I'm assuming this is because the <code>.shown</code> is placed onto the div during the same event loop as when <code>.foo</code> is placed onto the DOM. This tricks the browser into thinking that it was created with <code>opacity: 1</code> so no transition is put into place.</p>
  
  <p>I'm wondering if there is an elegant solution to this rather than wrapping my class in a setTimeout.</p>
  
  <p>Here's a snippet: </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var foo = $('&lt;div&gt;', {
      'class': 'foo'
  });
  
  foo.appendTo($('body'));
  
  setTimeout(function(){
      foo.addClass('shown');
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>.foo {
      opacity: 0;
      transition: opacity 5s ease;
      width: 200px;
      height: 200px;
      background-color: red;
  }
  
  .foo.shown {
      opacity: 1;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre>
  </div>
  </div>
  </p>