'Realtime color mode change if system color mode changed and color choice not being made

I've got a toggle for a color theme switcher for my website. Here's the JavaScript code for the theme switcher:

$('.theme-switch').on('click',
    function(e) {
        const valChoice = $('html').attr('data-theme') === 'dark' ? 'light' : 'dark';

        window.localStorage.setItem('themeChoice', valChoice);
        $('html').attr('data-theme', valChoice);
    }
);

This is working perfectly. I've got other scripts as well to remember a user's choice when a page loads after the theme choice. It also covers device color settings when a page loads.

I want to cover more than that. I'd like to see changes in real-time if a user changed device color settings when on a page. So I added the script:

window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change',
    function(e) {
        const colorScheme = e.matches ? 'dark' : 'light';

        if (colorScheme === 'dark') {
            $('html').attr('data-theme', 'dark');
        } else {
            $('html').attr('data-theme', 'light');
        }
    }
);

The code is working as expected. It responds if there is a change in device color settings. But there is a little problem!

Website color mode should not be changed to device mode if a user has chosen a theme on the running page by clicking the theme toggle. I mean, website mode should not be changed to device mode in real-time if a user has made a theme choice already in the current window.

Can anyone help me do that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source