Search code examples
javascriptjqueryfadeinfadeout

Add fade-in or fade-out on the addclass / removeclass event


I created an addclass and removeclass event :

$(".myclass").click(function(){
   $(".hiding").removeClass("hiding");
   $(this).addClass("hiding");
});

using the following CSS :

#wrapper a.hiding {
   display: none; 
}

and the HTML :

<div id="wrapper">
    <a class="myclass" href="#2">
        <img src="example.png">
    </a>
</div>

I can't seem to find a way to add a fade-in action when addclass is triggered. I would also like to add a fade-out when removeClass is triggered.

I have tried the following CSS without success:

 transition: all 0.5s ease;

Is there a better way through Javascript?


Solution

  • I recommend you try this

    edit: I realized just now using fadeIn() is better, try this:

    $(".myclass").click(function(){
       $(".hiding").fadeOut('slow', function() {
           $(".hiding").removeClass("oldStuffHere");
           $(this).addClass("newStuffHere");
           $(this).fadeIn('slow', function() {
               // Animation complete
                });
          });
    
    });