diff --git a/script.js b/script.js index 369d922..b027b37 100644 --- a/script.js +++ b/script.js @@ -1,13 +1,13 @@ (function (ThemeSwitcher) { const themeSwitcher = new ThemeSwitcher('stylesheet'); - const themeSwitch = document.getElementById('theme-switch'); + const themeSwitchBtn = document.getElementById('switch'); const themes = { dark: 'dark', darkStandalone: 'dark.standalone', light: 'light', lightStandalone: 'light.standalone' }; - const getSwitchThemePath = function () { + const getSwitchThemeName = function () { // Case: switch to "light.standalone.css" if ( (themeSwitcher.current === themes.dark) && themeSwitcher.isDark || @@ -37,21 +37,45 @@ return themeSwitcher.current; } }; + const getGeneralThemeName = function () { + return themeSwitcher.current.replace(/\.standalone/g, ''); + }; - themeSwitch.addEventListener('click', function() { - themeSwitcher.switch(getSwitchThemePath()); + themeSwitchBtn.addEventListener('click', function() { + themeSwitcher.switch(getSwitchThemeName()); }); + + themeSwitcher.onChangeDark = function () { + themeSwitcher.switch(getGeneralThemeName()); + }; + + themeSwitcher.onChangeLight = function () { + themeSwitcher.switch(getGeneralThemeName()); + }; })( (function () { const ThemeSwitcher = function(stylesheet) { const darkSchemeMql = matchMedia('(prefers-color-scheme: dark)'); const lightSchemeMql = matchMedia('(prefers-color-scheme: light)'); + const that = this; this.themeDir = '../dist/'; this.stylesheet = document.getElementById(stylesheet); this.current = this.getThemeName(this.stylesheet.href); this.isDark = darkSchemeMql.matches; this.isLight = lightSchemeMql.matches; + + darkSchemeMql.addListener(function (mql) { + if (mql.matches && typeof that.onChangeDark === 'function') { + that.onChangeDark() + } + }); + + lightSchemeMql.addListener(function (mql) { + if (mql.matches && typeof that.onChangeLight === 'function') { + that.onChangeLight() + } + }); }; ThemeSwitcher.prototype = { @@ -62,7 +86,9 @@ getThemeName: function () { const reg = new RegExp(this.themeDir + '(|.+?).css'); return stylesheet.getAttribute('href').replace(reg, '$1'); - } + }, + onChangeDark: null, + onChangeLight: null }; return ThemeSwitcher;