From ddbbf4bb7226dd5990898a97f0485d783619ea9e Mon Sep 17 00:00:00 2001 From: Phuntsok Drak-pa Date: Tue, 3 Sep 2019 02:04:57 +0200 Subject: [PATCH] Simplified javascript --- js/main.js | 60 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/js/main.js b/js/main.js index fb526ba..ee45c85 100644 --- a/js/main.js +++ b/js/main.js @@ -1,7 +1,5 @@ /*jshint esversion: 6 */ -var light = false; - window.onload = function() { reorganize_html(); create_theme_switcher(); @@ -65,34 +63,46 @@ function reorganize_html() { } function create_theme_switcher() { - // If no theme cookie is found, set dark by default - if (Cookies.get('theme') == null) { - Cookies.set('theme', 'dark'); - } + // set the correct CSS depending on the cookie, dark is default + var light = isThemeLight(); + $('body').append('
')); + $('head').append('')); - // set the css and button depending on the cookie found, dark is default - if (Cookies.get('theme') == 'light') { - $('body').append('
'); - $('head').append(''); - } else { - $('body').append('
'); - $('head').append(''); - } - - // switch CSS files and button icon, set new cookie + // switch CSS files and button icon, set new cookie on theme switcher click $('.themeBtn').click(function() { - if (Cookies.get('theme') == 'dark') { - $('link[href="./css/dark.css"]').attr('href', './css/light.css'); - $('.themeBtn').html(''); - Cookies.set('theme', 'light'); - } else { - $('link[href="./css/light.css"]').attr('href', './css/dark.css'); - $('.themeBtn').html(''); - Cookies.set('theme', 'dark'); - } + console.log("Theme change"); + var light = !isThemeLight(); + console.log(light); + $("#theme").first().attr('href', './css/' + .concat(light ? 'light' : 'dark') + .concat('.css')); + $('.themeBtn').html('')); + Cookies.set('light-theme', light ? 'true' : 'false'); }); } +function isThemeLight() { + // set the css and button depending on the cookie found, dark is default + var light; + switch (Cookies.get('light-theme')) { + case 'true': + light = true; + break; + case null: // If no theme cookie is found, set dark by default + Cookies.set('light-theme', false); + /* falls through */ + default: + light = false; + break; + } + return light; +} + + function isEmpty(el) { return !$.trim(el.html()); }