javascriptjquerycssanimationjquery-animate

Animate / apply Transition addClass and removeClass in jQuery?


I am new to jQuery & javascript and making a simple slider by adding and removing class 'active' on next slide which is working fine but seems ugly because there is no animation. Is there any way to animate the process of adding and removing a class? Like:

$('#next').on('click', function(){
    $('div.active').removeClass('active', duration: 500ms).next().addClass('active', duration: 500ms);})

At Jquery documentation website I have seen that there is an animate function which is used to animate things. Is it possible to use that function in my case?

Update: I have also tried to apply the CSS transition on div and div.active which is not working.

Css:

   .slider div {
        display: none;
        opacity: 0;
        -webkit-transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -ms-transition: opacity 1s ease-in-out;
        -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
    }

    div.active {
        display: inline-block;
        opacity: 1;
        -webkit-transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -ms-transition: opacity 1s ease-in-out;
        -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
    }

Solution

  • From comments of different users I came to know that css transition can not be applied on display: none elements. So instead of display none I applied height 0px; opacity: 0; which worked fine for me.

    .slider img{
     height: 0px;
     opacity: 0;
     display: block;
     -webkit-transition: opacity 2s ease;
     -moz-transition: opacity 2s ease;
     -ms-transition: opacity 2s ease;
     -o-transition: opacity 2s ease;
     transition: opacity 2s ease;
    }
    
    .slider img.active{
     height: 360px;
     opacity: 1;
     -webkit-transition: opacity 2s ease;
     -moz-transition: opacity 2s ease;
     -ms-transition: opacity 2s ease;
     -o-transition: opacity 2s ease;
     transition: opacity 2s ease;
    }
    

    Thanks to the creator of this fiddle which gave me this idea.