Search code examples
javascriptjquerycssthemestransition

jQuery transition between themes (when switching theme)


I have this:

<html lang="en" theme="dark">

and this:

html {
  &[theme='light'] {
    --bg: #ffffff;
    --title: #6822c4;
    --sub-title: #000000;
    --text: #ffffff;
  }
  &[theme='dark'] {
    --bg: #17171F;
    --title: #4578a5;
    --sub-title: #acacac;
    --text: #ffdddd;
  }
}

and this:

$('#myCheckBox').change(function() {
    if ($(this).is(':checked')) document.documentElement.setAttribute('theme', 'dark')
        else document.documentElement.setAttribute('theme', 'light')
});

and that's working perfectly BUT there is no transition, so I was wondering if I can deal something with jQuery, like a fadeOut or something?


Solution

  • Add transitions to the elements you want to change:

    $('#myCheckBox').change(function() {
      if ($(this).is(':checked')) document.documentElement.setAttribute('theme', 'dark')
      else document.documentElement.setAttribute('theme', 'light')
    });
    html[theme='light'] {
      --bg: #ffffff;
      --title: #6822c4;
      --sub-title: #000000;
      --text: #000000;
    }
    
    html[theme='dark'] {
      --bg: #17171F;
      --title: #4578a5;
      --sub-title: #eeeeee;
      --text: #ffffff;
    }
    
    body {
      background-color: var(--bg);
      transition: background-color 600ms linear;
    }
    
    label {
      color: var(--text);
      cursor: pointer;
    }
    
    h1 {
      color: var(--title);
    }
    
    h2 {
      color: var(--sub-title);
    }
    <html lang="en" theme="dark">
    
    <head>
      <meta charset="utf-8">
      <title>Test</title>
      <meta name="description" content="Test">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    
    <body>
      <label>Dark theme
    <input type="checkbox" id="myCheckBox" name="checkbox_theme" checked>
    </label>
      <h1>Title</h1>
      <h2>Sub-Title</h2>
    </body>
    
    </html>