smooth transition when icon font changes

Viewed 101

I'm making a dark mode button using an icon font and I was wondering if there's a way to have a smooth transition when changing from one icon to the next? The colors have a smooth transition, so that's not a problem, but the icons are changing faster than the colors. Here's the code:

$(document).ready(function() {
  $('.daynight').click(function() {
    $('body').toggleClass('night');
    $('.daynight span').toggleClass('th-sun');
  });
});
body.night {
  background: #292f36;
  color: white!important;
}

.daynight span {
  cursor: pointer;
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="daynight"><span class="th th-moon"></span></div>

I'm using transition: color 0.3s ease-in-out, background-color 0.4s ease-in-out; in my body tag to get the color transitions.

1 Answers

You can use jQuery .fadeToggle() to add a fade in/out animation to the icons. You need to have two absolutely positionned icons with one hidden onload.

Below, I used the FontAwesome icons set. I applied a 300ms delay to match the 0.3s transition for the body font color, but it could be a another delay...

$(document).ready(function () {
  $(".daynight").click(function () {
    $("body").toggleClass("night");
    $(".daynight span").fadeToggle(300);  // 300ms delay
  });
});
body {
  transition: color 0.3s ease-in-out, background-color 0.4s ease-in-out;
}

body.night {
  background: #292f36;
  color: white !important;
}

.daynight span {
  cursor: pointer;
  padding: 10px;
  position: absolute;
}

.fa.fa-sun {
  display: none;
  color: orange;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body class="night">
  <div class="daynight">
    <span class="fa fa-moon"></span><span class="fa fa-sun"></span>
  </div>
</body>

Related