theme-switcher.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // license information for librejs extension users
  2. // @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt "Expat License (sometimes called MIT Licensed)"
  3. // in Firefox we need to add a new css style with document.write rather than modifying the href
  4. // of the existing one, otherwise the screen will flash white while loading on dark themes
  5. var theme_css_elem = document.getElementById('theme_css');
  6. var js_url = document.currentScript.src; // example: http://example.com/myhugo/js/theme-switcher.js
  7. if(localStorage.getItem('theme') === 'dark'){
  8. var clone = theme_css_elem.cloneNode(false);
  9. clone.href = new URL("../css/themes/dark.css", js_url);
  10. theme_css_elem.remove();
  11. document.write(clone.outerHTML);
  12. }else if(localStorage.getItem('theme') === 'light'){
  13. var clone = theme_css_elem.cloneNode(false);
  14. clone.href = new URL("../css/themes/light.css", js_url);
  15. theme_css_elem.remove();
  16. document.write(clone.outerHTML);
  17. }
  18. window.addEventListener("load", function(event){update_toggle_button();}, false);
  19. function update_toggle_button(){
  20. var elem = document.getElementById('theme_css');
  21. var button = document.getElementById('change-theme-button');
  22. button.style.display = "";
  23. if(elem.href.endsWith('light.css')){
  24. button.getElementsByTagName('img')[0].src = new URL('../images/theme-switcher-moon.svg', js_url);
  25. }else if(elem.href.endsWith('dark.css')){
  26. button.getElementsByTagName('img')[0].src = new URL('../images/theme-switcher-sun.svg', js_url);
  27. }
  28. }
  29. function toggle_theme(){
  30. var elem = document.getElementById('theme_css');
  31. if(elem.href.endsWith('light.css')){
  32. elem.href = new URL("../css/themes/dark.css", js_url);
  33. localStorage.setItem('theme', 'dark');
  34. }else if(elem.href.endsWith('dark.css')){
  35. elem.href = new URL("../css/themes/light.css", js_url);
  36. localStorage.setItem('theme', 'light');
  37. }
  38. update_toggle_button();
  39. }
  40. // @license-end