Sadegh Shaikhi Sadegh Shaikhi - 1 year ago 68
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 Source

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

  $('#target').toggleClass("hidden show");
#target {
  background: green;
<script src=""></script>
<button class="show_hide">Show / Hide</button>
<div id="target" class='show'></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download