-1

When animating an element to disappear with opacity: 0, then setting the display property to 'none' to remove it from view, display:none gets executed instantly, is there anyway to wait for the animation to complete before removing it from view with display:none

Here is the following example: http://jsfiddle.net/zg3q7jLt/38/

var box = document.querySelector('#box');

function addCssTransition(elem, speed) {
                elem.style.cssText +=
                    ';transition: all ' + speed + 's ease-in-out; ' +
                    '-moz-transition: all ' + speed + 's ease-in-out;' +
                    '-webkit-transition: all ' + speed + 's ease-in-out';
}

function fadeOut(elem, speed){
        addCssTransition(elem, speed);
        elem.style.opacity = 0;
        elem.style.display = 'none';
}

fadeOut(box, 0.75);
AntonB
  • 2,724
  • 1
  • 31
  • 39

2 Answers2

1

You could listen for transition-end events, but that's problematic and in flux at the moment.

Your safest bet is probably a setTimeout():

function fadeOut(elem, speed){
  addCssTransition(elem, speed);
  elem.style.opacity = 0;

  setTimeout( function() { elem.style.display = 'none'; }, speed * 1000 );
}
Community
  • 1
  • 1
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • Just curious, why the 1000ms? is that the correct amount to calculate the fading? – AntonB Jan 15 '15 at 19:09
  • 1
    You're passing `speed` in seconds (as appropriate for transitions). `setTimeout()` takes milliseconds. Multiplying by 1000 matches things up. – Paul Roub Jan 15 '15 at 19:15
0

Display: none doesn't have a transition because you can't partially display.

You can setTimeout like this:

var box = document.querySelector('#box');

function addCssTransition(elem, speed) {
                elem.style.cssText +=
                    ';transition: all ' + speed + 's ease-in-out; ' +
                    '-moz-transition: all ' + speed + 's ease-in-out;' +
                    '-webkit-transition: all ' + speed + 's ease-in-out';

setTimeout(function(){ 
 elem.style.cssText +=
                    ';display:none';

}, speed);
}

function fadeOut(elem, speed){
        addCssTransition(elem, speed);
        elem.style.opacity = 0;
        elem.style.display = 'none';
}

fadeOut(box, 0.75);
itamar
  • 3,837
  • 5
  • 35
  • 60