javascripthtmlcsslight

Transition on light/dark mode


I did the code for dark/light mode this way, using Javascript and CSS. but I can't find anywhere a way to add a transition on changing the light/dark modes.

CSS

 :root {
    --primary-bg-color: #F5F5F5;
    --secondary-bg-color: #FFFF;
    --primary-text-color: #2B283A;
    --secondary-text-color: #4A4E74;
}

    .dark-theme {
    --primary-bg-color: #3A69D2;
    --secondary-bg-color: #1F2937;
    --primary-text-color: #FFFF;
    --secondary-text-color: #F5F5F5;
}

JS

icon.onclick = function() {
    document.body.classList.toggle("dark-theme")
    if(document.body.classList.contains("dark-theme")){
        icon.src = "sun.png"
    }else {
        icon.src = "moon.png"
    }
}

Solution

  • Try getting the element by its id and then set its image source

    icon.onclick = function() {
        document.body.classList.toggle("dark-theme")
        if(document.body.classList.contains("dark-theme")){
            document.getElementById("myIcon").src = "sun.png";
        }else {
            document.getElementById("myIcon").src = "moon.png";
        }
    }
    

    Example: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_src2