Home > Enterprise >  How to change toggle button dark mode smoothly
How to change toggle button dark mode smoothly

Time:01-31

I made a toggle button for dark mode, it is working good. I want the switching between the dark mode and back going smoothly, How can I fix this?

<button onclick="myFunction()">Toggle dark mode</button>

function myFunction() {
    var elements = document.querySelectorAll(".one, .three, .five");
    elements.forEach(function (element) {
        element.classList.toggle("dark-mode");
        if (element.classList.contains("dark-mode")) {

/the rest of code is just color and background settings/

I tryed to search for the answer on stackoverflow but couldn't find any answer.

CodePudding user response:

.one,
.three,
.five{
    transition:color 500ms,background-color 500ms,border 500ms;
}

I think this should do the trick

CodePudding user response:

To add a transition in this JS code, you need to define the CSS properties that are to be animated and the duration of the transition. For example:

In this example, we are defining a transition for the background-color property with a duration of 0.5s and an ease-in-out easing function.

function myFunction() {
    var elements = document.querySelectorAll(".one, .three, .five");
    elements.forEach(function (element) {
        element.classList.toggle("dark-mode");
        if (element.classList.contains("dark-mode")) {
            element.style.transition = "background-color 0.5s ease-in-out";
        } else {
            element.style.transition = "background-color 0.5s ease-in-out";
        }
       
       /*continuous js code*/

Please enter more on your code to get more help.

  • Related