Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to change a css file with clicking on a button?

I have a root css style file and I have defined some color variables in that. for ex:

--background-blue-primary: #005a9e;

Also, in my main html file there is a button to change theme. when someone clicked on that, i want the color code in variable to change.
how can i do that?


MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Like this

document.getElementById('themeChangeButton')
  .addEventListener('click', () => document.documentElement.style
    .setProperty('--background-blue-primary', '#ff4500')); 
:root {
  --background-blue-primary: #005a9e;
}

body {
  background-color: var(--background-blue-primary);
}
<div class="content">
  This is some content to see the effect of theme change.
</div>

<button id="themeChangeButton">Change Theme</button>

or

document.getElementById('themeChangeButton')
  .addEventListener('click', () => document.body.style.backgroundColor = '#ff4500');
:root {
  --background-blue-primary: #005a9e;
}

body {
  background-color: var(--background-blue-primary);
}
<div class="content">
  This is some content to see the effect of theme change.
</div>

<button id="themeChangeButton">Change Theme</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading