1

I'm trying to use the classList api combined with CSS transitions to prepend an item to a list, remove a class that's making it transparent, and then fade it in.

html

<ul id="container">
    <li>test1</li>
    <li>test2</li>
    <li>test3</li>
    <li>test4</li>
</ul>

css

.is-transparent {
    opacity: 0;
}

#container {
    li {
        -webkit-transition: opacity 2.3s;
        -moz-transition: opacity 2.3s;
        transition: opacity 2.3s;
        &.is-transparent {
            opacity: 0;
        }
    }
}

js

function runner() {
    var container = document.getElementById('container');
    var newItem = document.createElement('li');

    // item attrs
    newItem.innerText = 'test Above';
    newItem.classList.add('is-transparent');

    // do work
    container.insertBefore( newItem, container.firstElementChild );

    // transition opacity (ideally)
    newItem.classList.remove('is-transparent');
}

I'd expect this to work since the class gives it 0 opacity and when it's removed it should have opacity: 1; but it doesn't: http://jsfiddle.net/7TpY6/1/

Adding a setTimeout of 0 (as follows) makes the transition work: http://jsfiddle.net/3N2Bn/1/

window.setTimeout(function(){
    newItem.classList.remove('is-transparent');
}, 0);

Why?

imjared
  • 19,492
  • 4
  • 49
  • 72

0 Answers0