0

I have an element that I've changed the style of (Either through changing the class or modifying the style).

I then wish to add a transition so that later changes will be animated.

For some reason, when I set the style before the transition, the style is still animated. This is happening in the latest versions of Firefox, Chrome, and Safari.

Example: http://codepen.io/DavidBradbury/pen/IxfmF

JS Snippet [Library is jQuery but it shouldn't matter]:

$(function() {
  $("#toggle").on({
    click: function(e) {
      // ## Change the class / style
      // At this point, it shouldn't know that
      // a transition will be added
      $("#badidname").toggleClass('newclass');

      // Then add the transition
      $("#badidname").css({
        "transition": "all 600ms"
      });

      // For some reason, it animates 
      // the class being added
    }
  })
})
David Bradbury
  • 1,997
  • 3
  • 19
  • 23

1 Answers1

1

You need to wrap the transition in a timeout:

setTimeout(function() { $("#badidname").css({ "transition": "all 600ms" }); }, 0);

Here's a great explanation over the oddness of setTimeout(..., 0); setTimeout with zero delay used often in web pages, why?

Community
  • 1
  • 1
André Dion
  • 21,269
  • 7
  • 56
  • 60