Alexander Solonik
Alexander Solonik

Reputation: 10230

Transition applying when element added , not removed

i was working on a small transition effect , where the background color of div changes every 4's , the problem is that , the bg color changes with a transition only when adding the bg color and not removing the bg color :

The HTML ::

<div class="test-it" id="test-it">
    HELLO
</div> 

THE CSS ::

.test-it {
    height: 200px;
    width: 200px;
    background: #eee;
    line-height: 200px;
    text-align: center;
    font-family: verdana;
    text-transform: uppercase;
    color: #fff;
    font-size: 40px;
    font-weight: bold;
}

.red {
    background: red;
    -webkit-transition: 2s;
    -o-transition: 2s;
    transition: 2s;
}

and the JS code ::

(function() {

    var apollo = {};

    apollo.hasClass = function(elem, className) {
        return elem.classList.contains(className);
    };

    apollo.addClass = function(elem, className) {
        elem.classList.add(className);
    };

    apollo.removeClass = function(elem, className) {
        elem.classList.remove(className);
    };

    apollo.toggleClass = function(elem, className) {
        elem.classList.toggle(className);
    };

    window.apollo = apollo;

})();

apollo.addClass(document.body, 'test');

apollo.addClass(document.getElementById('test-it'), 'red');

var $str = apollo.hasClass(document.getElementById('test-it'), 'red');


var run = function() {

    setTimeout(function() {
        apollo.toggleClass(document.getElementById('test-it'), 'red');
        setTimeout(function() {
            run();
        }, 2000);

    }, 2000);

}

run();

console.log($str);

Don't really look into the JS code much , as the error or desired behavior needs to be in CSS , so can somebody explain why is it that the transition is not applied when the class .red is taken off ??

the class .red has the following CSS ::

.red {
    background: red;
    -webkit-transition: 2s;
    -o-transition: 2s;
    transition: 2s;
}

so why is the 2 second transition not applicable when when the class is taken off ??

Thank you.

Alex-z.

Upvotes: 0

Views: 32

Answers (1)

Brian Leishman
Brian Leishman

Reputation: 8555

You need to apply your transitions to the main element, because once you remove the .red class, the transitions are no longer part of the element, thus, no transitions.

So your CSS should look like this

.test-it {
                height: 200px;
                width: 200px;
                background: #eee;
                line-height: 200px;
                text-align: center;
                font-family: verdana;
                text-transform: uppercase;
                color: #fff;
                font-size: 40px;
                font-weight: bold;
                -webkit-transition: 2s;
                -o-transition: 2s;
                transition: 2s;
            }
            .red {
                background: red;
            }

Upvotes: 2

Related Questions