8
votes

I want to know how to animate JQuery addClass/removeClass functions?

for animate function, it seems that I have to put some CSS properties, but what about if I have a class which makes element displayed as block each time I trigger a click function, while all elements are displayed as hidden in CSS. How can I animate this process?

Here's my code:

<script src="js/jquery-1.9.1.min.js"></script>
<script>

    var allSlides = $('li');

    $('#nextSlide').click(function(){
        var nextSlide = $('.active').next();
        if (nextSlide.length == 0)
        {
            var nextSlide = allSlides.first();
        }
        $('.active').removeClass('active');
        nextSlide.addClass('active');
        return false;
    });

    $('#prevSlide').click(function(){
        var prevSlide = $('.active').prev();
        if (prevSlide.length == 0)
        {
            var prevSlide = allSlides.last();
        }
        $('.active').removeClass('active');
        prevSlide.addClass('active');
        return false;
    });

</script>
4
Hello CairoCoder find the solution below :) - Ibnul Hasan

4 Answers

15
votes

You can apply the CSS3 transition property to the element being manipulated with jQuery. Here's an example with vendor prefixes:

element {
    -webkit-transition: all 2s; // Chrome
    -moz-transition: all 2s; // Mozilla
    -o-transition: all 2s; // Opera
    transition: all 2s;
}
2
votes

If you're using jQueryUI you can use the $.toggleClass(); function.

http://api.jqueryui.com/toggleClass/

1
votes

You can use jQuery .fadeIn() or you can use CSS3 transitions:

#nextSlide, #prevSlide {
  display: none;
  -webkit-transition: display .5s ease;
  -moz-transition: display .5s ease;
  -o-transition: display .5s ease;
}
.active {
  transition: display .5s ease;
  -webkit-transition: display .5s ease;
  -moz-transition: display .5s ease;
  -o-transition: display .5s ease;
}

That should work for you. You can add any other transitions to by replacing display in the transition style.

0
votes

You can definitely animate to add/remove class with jquery.Please check the format below

.removeClass( className [, duration ] [, easing ] [, complete ] )

Example code below

$( "div" ).click(function() {
   $( this ).removeClass( "big-blue", 1000, "easeInBack" );
});

Reference link

NOTE: But you've to add jquery-ui.js file to make it work.

<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Hope this will be helpful. Thanks