add css transition time to toggle class using javascript

25,437

Try add the rule for transition in your target class itself.

.class1 {
    color: #f00;
    background-color: #2fadac;
   -webkit-transition: all 0.5s ease-in-out;
}

.class2 {
    color: #00f;
    background-color: #c33;
    -webkit-transition: all 0.5s ease-in-out;

}

Demo

Or just apply the rule in a separate rule:

CSS:-

.class1 {
    color: #f00;
    background-color: #2fadac;
}

.class2 {
    color: #00f;
    background-color: #c33;
}
.transition{
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition:all 0.5s ease-in-out;
  -o-transition:all 0.5s ease-in-out;
  transition:all 0.5s ease-in-out;
}

HTML:

<div id="div" class="class1 transition">click here</div>

Demo

Share:
25,437

Related videos on Youtube

user2906766
Author by

user2906766

Updated on November 21, 2020

Comments

  • user2906766
    user2906766 over 3 years

    I want to add a transition time to my pure javascript toggle class function I knew how to code it but i forgot and now need some advice

    <!DOCTYPE html>
    <html>
    <head>
    
    <style type="text/css">
    #div{
        width: 200px;
        height: 150px;
    }
    .class1 {
        color: #f00;
        background-color: #2fadac;
    }
    
    .class2 {
        color: #00f;
        background-color: #c33;
    }
    </style>
    </head>
    <body>
    <div id="div" class="class1">click here</div>
    <script>
    function classToggle() {
        this.classList.toggle('class1');
        this.classList.toggle('class2');
        style.cssText ="-webkit-transition: all 0.5s ease-in-out;";
    }
    document.querySelector('#div').addEventListener('click', classToggle);
    </script>
    </body>
    </html>
    

    any help would be appreciated