Palm
Palm

Reputation: 360

JavaScript Toggle class

'use strict'

const switcher = document.querySelector('.btn');
console.log(switcher);

switcher.addEventListener('click', function() {
    document.body.classList.toggle('dark-theme');

    let className = document.body.className;
    if (className == "light-theme") {
        this.textContent = "Dark";
    }
    else {
       this.textContent = "Light";
    }
});

Not sure how the toggle works. How is when I click the button the background changes back to the light-theme when the script doesn't even specify to change back to light-theme?

Upvotes: 2

Views: 3923

Answers (2)

Root
Root

Reputation: 132

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Theme</title>
   
</head>
<body class="light-theme">


  <div>
    <button type="button" class="btn">Dark</button>
  </div>
      
      
 
  <script type="text/javascript">

'use strict'

const switcher = document.querySelector('.btn');
console.log(switcher);

switcher.addEventListener('click', function() {
    document.body.classList.toggle('dark-theme');
    document.body.classList.toggle('light-theme');

    let className = document.body.className;
    if (className == "light-theme") {
        this.textContent = "Dark";
    }
    else {
       this.textContent = "Light";
    }
});
  </script>
</body>
</html>

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371233

It's the document.body.classList.toggle('dark-theme');.

If that class exists, it is removed. If that class doesn't exist, it is added.

Your button changes the HTML from

<body class="light-theme">

to

<body class="light-theme dark-theme">

and back again.

Using CSS rules, if two rulesets with the same specificity are declared, and one is declared below the other, the one below will take precedence if both apply to an element. So

.light-theme {
  /* rules */
}
.dark-theme {
  /* rules */
}

will mean that if an element has dark-theme and light-theme, dark-theme's rules will override any duplicate styles applied by light-theme.

Upvotes: 3

Related Questions