Sadegh Shaikhi Sadegh Shaikhi - 1 month ago 6
Javascript Question

How to add a fade effect when changing classes?

I don't know how to add an animation effect when the classes are changed.

Here is my code:

$("#a-button").click(function() {
$("#a-div").toggleClass("hidden show");
});


This works but it doesn't have any effect when changing the classes.I want to make it smoother, maybe something like fading in and out. How can i do that?

Answer

You could use fadeOut()/fadeIn() with hasClass() condition to check the if the div has a specific class:

$('.show_hide').click(function() 
{
  if($('#target').hasClass('show'))
    $('#target').fadeOut('normal');
  else
    $('#target').fadeIn('normal');
    
  $('#target').toggleClass("hidden show");
});
#target {
  background: green;
  margin-bottom:15px;
  height:150px;
  padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="show_hide">Show / Hide</button>
<div id="target" class='show'></div>

Comments