summaryrefslogtreecommitdiff
path: root/templates/web/js/colorscheme-switcher.js
blob: dc0a7bda452b731957f0f29d1caba72935c79798 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var theme_switch = document.getElementById("dark-light-switch");
var body = document.getElementsByTagName("BODY")[0];



function init( color ){
  change(color, true);
  localStorage.setItem('color', color);
  theme_switch.setAttribute("color", color);
}

function change(color, nowait){
  // Discard transition is nowait is set
  if(nowait !== true){
    window.setTimeout(function() {
      document.documentElement.classList.remove('color-theme-in-transition')
    }, 1000)
    document.documentElement.classList.add('color-theme-in-transition');
  }

  document.documentElement.setAttribute('data-theme', color);
  theme_switch.setAttribute("color", color);
  localStorage.setItem("color", color);
}

function theme_change_requested(){
  color = theme_switch.getAttribute("color");
  if(color=="light")
    change("dark");
  else
    change("light");
}

function getCurrentColor(){
  // Color was set before in localStorage
  var storage_color = localStorage.getItem("color");
  if(storage_color !== null){
    return storage_color;
  }

  // If local storage is not set check the background of the page
  // This is dependant of the CSS, be careful
  var background = getComputedStyle(body).getPropertyValue("background-color");
  if(background == "rgb(255, 255, 255)") {
    return "light";
  } else {
    return "dark";
  }
}

init( getCurrentColor() )
theme_switch.addEventListener("click", theme_change_requested);