1

HTML

<ul class="container" >
   <li class="default-state"> 
      some stuff 
   </li>
</ul>

SASS

.default-state
  transition: all 0.2s ease 0s
  width: 20px

.new-state
  width: 100px

JS

$itemClone = $('li.default-state').clone();
$('ul').append($itemClone);
$itemClone.addClass('new-state');

What's happening is the div appears in the list with its class already as '.new-state', and no transition is applied.

What I find absurd is when I do this:

$itemClone = $('li.default-state').clone();
$('ul.container').append($itemClone);
setTimeout(function(){
   $itemClone.addClass('new-state');
}, 1);

It works perfectly. But I feel like using .delay() or setTimeout should be unnecessary in this scenario. I know.append() doesn't have a callback function, is there another jquery method that I could add to this to avoid adding stupid 1ms delays?

I want to keep all my transitions/animations in SASS because the widths are dynamic on media queries.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • Looks like you just have to use a delay or timeout: https://stackoverflow.com/questions/6068955/jquery-function-after-append - think the problem is because your itemClone exists in memory, you can add the class to it before it has finished rendering in the DOM – Pete Nov 21 '18 at 11:09
  • I found this question which has the best solution I've seen: [https://stackoverflow.com/questions/24148403/trigger-css-transition-on-appended-element]. Accessing a CSS property essentially forces a reflow, so adding `$itemClone.css('any property);` does the job without using timeouts or delays. Although I still think .append() should have a flag or something that forces a reflow. – Oliver Pearson Nov 21 '18 at 11:37
  • haha, I must have had the same problem in the past - I've upvoted that question and answer! – Pete Nov 21 '18 at 11:38

0 Answers0