简体   繁体   中英

Dark mode toggle

I've been trying to create a logic to toggle the button (images) back and forth and switch between styles (light/dark mode) infinitely, but I'm failing to do so. Can you give me some clue how this can be accomplished?

With this code I am succeeding to toggle styles only once...

let toggleDark =
    document.getElementById('btn-toggle').addEventListener('click', function() {
    document.querySelector('body').style.backgroundColor = 'black';
    document.querySelector('body').style.color = 'white';
    document.querySelector('.sun').style.visibility = 'hidden';
    document.querySelector('.moon').style.visibility = 'visible';

    toggleLight();
});

function toggleLight() {
    document.getElementById('btn-toggle').addEventListener('click', function() {
    document.querySelector('body').style.backgroundColor = 'white';
    document.querySelector('body').style.color = 'black';
    document.querySelector('.sun').style.visibility = 'visible';
    document.querySelector('.moon').style.visibility = 'hidden';
})};

Here's the HTML part...

<body class="dark light">

<div>
    <button id="btn-toggle">
        <img src="weather-sunny.png" alt="Light Mode" id="light_mode" class="sun">
        <img src="weather-night.png" alt="Dark Mode" id="dark_mode" class="moon">
    </button>
</div>

<main>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero quo, officiis repellat quam accusantium neque pariatur! Facilis nemo enim cumque atque, eaque perferendis corporis aliquid, temporibus, incidunt, sint sed sunt.</p>
</main>

If you add the same eventListener to the same element, both will execute after both are set. It won't toggle between, and you could do this in one function with a Boolean.

Note : Change the toggled to true if the beginning mode is white and false if it's black.

function colormode(toggle) {
    document.querySelector('body').style.backgroundColor = (toggle) ?'black':'white';
    document.querySelector('body').style.color = (toggle) ? 'white':'black';
    document.querySelector('.sun').style.visibility = (toggle) ? 'hidden':'visible';
    document.querySelector('.moon').style.visibility = (toggle) ? 'visible':'hidden';
};

var toggled = false;
document.getElementById('btn-toggle').addEventListener('click', function() {
   colormode(toggled);
   toggled = !toggled;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM