Home > Mobile >  trying to toggle stylesheet using button
trying to toggle stylesheet using button

Time:01-30

I am attempting to switch stylesheets on my website using a button.

When I use this code, the stylesheet becomes nonexistent when I press the button and I cannot switch back unless I refresh the site. I do not know what is happening.

JavaScript

 const stylesUrls = ["C:\Users\purrl\OneDrive\Desktop\Personal Coding\html\claires.css", "C:\Users\purrl\OneDrive\Desktop\Personal Coding\html\queen-of-hearts.css"];

      window.onload = function(){
           let switcherBtn = document.getElementById("themes");

            switcherBtn.onclick = function() {
                      let style = document.getElementById('ss');
                      let stylesUrl = stylesUrls.shift();
                      style.href = stylesUrl;
                      stylesUrls.push(stylesUrl);
                  
            }
        };

HTML

<link rel="stylesheet" href='C:\Users\purrl\OneDrive\Desktop\Personal Coding\html\claires.css' id="ss" type="text/css">
<button id="themes" type="button">Switch Theme</button>

CodePudding user response:

Store the current index in a variable and change that instead.

const stylesUrls = ["foo", "bar"];

window.onload = function() {
  const switcherBtn = document.getElementById("themes");
  let currentIndex = 0;

  switcherBtn.addEventListener("click", function() {
    let style = document.getElementById('ss');
    let stylesUrl = stylesUrls[currentIndex];
    style.href = stylesUrl;
  
    if (currentIndex === 0) {
      currentIndex = 1;
    } else {
      currentIndex = 0;
    }
  });
}

If you're trying to do themes, you can change a class on the root html tag and include a style tag to both stylesheets and then use the corresponding class in each stylesheet.

Example

queen-of-hearts.css;

html.queen h1 {
  color: red;
  font-size: 20px;
}

html.queen div {
  background-color: pink;
}

claires.css;

html.claire h1 {
  color: blue;
  font-size: 30px;
}

html.claire div {
   background-color: green;
}

HTML;

<html > <!-- Toggle between queen and claire using JavaScript -->
  <head>
    <link href="insert link to claires.css here" />
    <link href="insert link to queen-of-hearts.css here" />
  </head>
</html>

JS;

...
switcherBtn.addEventListener("click", function() { 
  if (document.documentElement.classList.contains("claire")) {
    document.documentElement.classList.replace("claire", "queen");
  } else {
    document.documentElement.classList.replace("queen", "claire");
  }
});

Demo

  • Related