0

So I've been messing around with JS, and I wanted to make a dark theme toggle button as seen here.

However, that tutorial only shows how to make it work with the <style> tag in HTML, not using an external CSS file.

How could I make it toggle the class .d_theme from an external CSS file?

  • 3
    Please visit help center, take [tour](https://stackoverflow.com/tour) to see what and [How to Ask a good question](https://stackoverflow.com/help/how-to-ask). Do some research, [search](https://stackoverflow.com/search) for related topics on Stackoverflow; if you get stuck, post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) so that an answer to that can be provided. – Always Helping Sep 29 '20 at 12:14
  • Where the class is defined in CSS is completely irrelevant to whether or not you can toggle it in the DOM. Where exactly are you stuck? – str Sep 29 '20 at 12:17
  • _Nikhil suggested_ Search Before asking the question you have many options to change the CSS file [Replacing css file on the fly (and apply the new style to the page)](https://stackoverflow.com/questions/19844545/replacing-css-file-on-the-fly-and-apply-the-new-style-to-the-page) – mplungjan Sep 29 '20 at 12:21
  • Please attempt to do something and if it doesn't work, show any errors that occur. The tutorial, in fact, does not dictate where the CSS is stored. – Heretic Monkey Sep 29 '20 at 12:29

1 Answers1

0

No difference between external and internal CSS when you use JS to toggle

document.getElementById("chk").addEventListener("change",function() {
  document.getElementById("x").classList.toggle("mystyle",this.checked)
})
/* This can be in an external file */
.mystyle {
  width: 100%;
  padding: 25px;
  background-color: coral;
  color: white;
  font-size: 25px;
  box-sizing: border-box;
}
<label><input type="checkbox" id="chk">Change theme</label>
<div id="x">Here is some text</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236