Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

karimali1337's avatar

Dark theme toggle

I'm trying to make light/light theme for a table in my project,its dark by default so i'm trying to change it to light when i click on the button but when i click it changes to light but not turning back any hints ?

var element = document.getElementById('toggleTheme')
var attributeContent = element.getAttribute('data-layout-mode')
let toggleTheme = document.querySelector(".light-dark-mode");
let styleSheet = document.querySelector("#color-theme");

console.log(attributeContent);

if (attributeContent=="dark") {
    toggleTheme.addEventListener("click", () => {
        styleSheet.setAttribute("href", "")

        })
} else if (attributeContent=="light") {
    toggleTheme.addEventListener("click", () => {
        styleSheet.setAttribute("href", "{{ asset('css/style.css') }}")

        })
} else {
            console.log("not found")
}
0 likes
2 replies
Sergiu17's avatar
Sergiu17
Best Answer
Level 60
<link rel="stylesheet" href="light.css">
<link id="dark-theme" rel="stylesheet" href="dark.css">
// ..
<button>Change theme</button>
<script>
    btn = document.querySelector('button');
    link = document.querySelector('#dark-theme');

    btn.addEventListener('click', function () {
        link.attributes.href.value === ''
        ? link.setAttribute('href', 'dark.css')			
        : link.setAttribute('href', '')
    });
</script>

in your case it does not work, because you add an event listener inside if statement, and it will always set your theme to white, instead add your if statement inside event listener

toggleTheme.addEventListener("click", () => {
  if (attributeContent=="dark") {
    //
  } else if (attributeContent=="light") {
    //
  } else { console.log(''); }
});

Please or to participate in this conversation.