j roc
j roc

Reputation: 238

jquery toggleClass with fade in effect

I'm using jQuery to toggle between my light theme and dark theme:

$(".theme__switch").on("click", () => {
  $("body").toggleClass("light__theme dark__theme");
});

My goal is to attach a fade-in animation to both these classes.

It works for light__theme on load, and when I toggle back from dark__theme, but when I try to add the fade-in animation to my dark__theme, the animation doesn't work for either themes

I start with: <body class="light__theme">

.light__theme {
  animation: fadein 2s;
}

@keyframes fadein {
  from {
      opacity:0;
  }
  to {
      opacity:1;
  }
}

which works fine, but when I try to attach the animation to my dark__theme class like so:


.dark__theme {
  --background: #121212;
  --text: #f2f3f4;
  background: var(--background);
  
  // adding the animation in
  animation: fadein 2s;

}

I don't get the fade-in animation, and it also removes the animation from my light theme.

The classes are being toggled correctly, I can see that when inspecting the <body> in dev tools, but I'm not sure whats causing my issue. Perhaps the way I'm calling the animation in my css?

I'd really appreciate any help on this one.. thanks for looking!

Upvotes: 0

Views: 252

Answers (1)

Rojo
Rojo

Reputation: 2869

You need to add reverse to the animation for dark__theme:

.dark__theme {
  --background: #121212;
  --text: #f2f3f4;
  background: var(--background);
  
  // adding the animation in
  animation: fadein 2s reverse;

}

Animation MDN

Upvotes: 1

Related Questions