skip to Main Content

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?


2

Answers


  1. 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>
    Login or Signup to reply.
  2. Declare 2 variables as you want.

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

    On clicking a button, just add a custom class "green_theme" to the BODY tag or DIV using Javascript.

    <script>
            // JavaScript to add class on button click
            document.getElementById('addClassButton').addEventListener('click', function() {
                document.body.classList.add('green_theme');
            });
        </script>
    

    If you use jQuery, use below code.

    <script>
            // jQuery code to add class on button click
            $(document).ready(function() {
                $('#addClassButton').click(function() {
                    $('body').addClass('green_theme');
                });
            });
        </script>
    

    Write the CSS by targeting the ‘green_theme’ class.

    .green_theme .button{background-color:var(--background-green-primary);}
    

    Change the Classname (green_theme), Button ID (#addClassButton) and CSS Variables accordingly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search