3

I've created a new element using jquery and then appended it to my DOM.

I then show two other elements and then finally add a css class which transitions in the newly created element.

However it doesnt transition in unless i wrap it in setTimeout of even just one millisecond.

setTimeout(function(){
    $('.modal-window').addClass('modal-animate-in');
},1)

I've stepped through the code line by line in chrome and then it seems to animate in when it gets to the right line otherwise it needs some kind of delay. Whats going on?

How can i even debug this?

I could just leave it with the setTimeout but that would be bad practise, and i would like to understand whats going on.

EDIT

Firefox is the same but requires a few more milliseconds timeout

Dustin Silk
  • 4,320
  • 5
  • 32
  • 48
  • Great question, I would believe this is because jQuery or the DOM isn't finished making changes to the element, so when you call `addClass` there's nothing ready to manipulate -- though I'm not sure enough to write a discreet answer. – Albert Xing Mar 19 '14 at 20:49
  • 1
    This is almost guaranteed to be a concurrency / race-condition issue. Putting the `addClass` in a 1 (or 0) `ms` timeout moves the animation to the end of the javascript event stack. Someone who knows more about this than me can probably explain it better. **EDIT**: in fact, here's a simple explanation: http://stackoverflow.com/a/779785/597122 (and I'll be marking as duplicate, because that should be your answer: wait until the DOM repaint is done before adding classes). – rockerest Mar 19 '14 at 20:49
  • I did a console log of the new elements class just before the addClass and it returns the dom element as if it does exist already – Dustin Silk Mar 19 '14 at 20:51
  • It definitely does exist at that point (dom manipulations are all synchronous), however it may not be rendered yet. if you add an element and give it the class at the same time, it will render with the class causing i to not animate. – Kevin B Mar 19 '14 at 20:51
  • what happens if you dont set a value for the time out `setTimeout(function(){ $('.modal-window').addClass('modal-animate-in'); })` out of interest – andrew Mar 19 '14 at 20:52
  • @andrew in webkit browsers it then played the transition, but not in firefox. – Dustin Silk Mar 19 '14 at 20:57
  • 3
    The answer is full explained here [css transitions on new elements](http://stackoverflow.com/questions/12088819/css-transitions-on-new-elements) including the difference in timing between Firefox and Chrome. I've marked this as a duplicate. – jfriend00 Mar 19 '14 at 20:58

0 Answers0