user14727395
user14727395

Reputation:

ease transition on night mode button

I have a simple JavaScript light/dark mode button but I don't know how to make the transition ease out as well as in. Here's the CSS:

.night-mode {
  background-color:#2a2d30;
  color:white;
  transition:0.4s ease-in-out;
}

Here's the JS and HTML:

<button onclick="night()">night mode</button>

<script>
function night() {
   var element = document.body;
   element.classList.toggle("night-mode");
}
</script>

Upvotes: 2

Views: 1399

Answers (2)

Dario Piotrowicz
Dario Piotrowicz

Reputation: 1092

The problem is that you put the transition in the class you're setting/removing, it should be independent from it.

What I would do, if you're just changing the body element is to set up the transition in that as:

body {
  transition: color .4s ease-in-out, background-color .4s ease-in-out;
  /* set the light colors here if needed */
}

.night-mode {
  background-color:#2a2d30;
  color:white;
}

Note that in the code above I don't set the transition for every single property but only for those which we actually want to be animated.

Naturally if you want the animation to work not on just the body but specific elements (for example some parts of your UI need to remain the same, also for example link don't inherit the colors) I would create an utility class like:

   .with-colors-transition {
      transition: color .4s ease-in-out, background-color .4s ease-in-out;
      /* set the light colors here if needed */
   }

and apply that to all the elements you want to add/remove the night-mode

Upvotes: 2

Rojo
Rojo

Reputation: 2869

You can do this if you add another class called dark-mode-off. Then, set the body class to that. In the JS, add a global variable to check if darkmode is on or off. Depending on that, replace the current class with the other one.

var darkmodeon = false;
function night() {
  var element = document.body;
  if (darkmodeon) {
    element.classList.replace("night-mode-on", "night-mode-off");
  } else {
    element.classList.replace("night-mode-off", "night-mode-on");
  }
  darkmodeon = !darkmodeon;
}
.night-mode-on {
  background-color: #2a2d30;
  color: white;
  transition: 0.4s ease-in-out;
}
.night-mode-off {
  background-color: #fff;
  color: black;
  transition: 0.4s ease-in-out;
}
<body class="night-mode-off">
  <button onclick="night()">night mode</button>
</body>

To avoid a lengthy if statement, you can make it one line:

element.classList.replace(darkemodeon ? "night-mode-on" : "night-mode-off", darkemodeon ? "night-mode-off" : "night-mode-on");

Upvotes: 1

Related Questions