skip to Main Content

I got this code online, I’m confused as to how I can get the background colour to change when the button is toggled. How would I get it to change colour when the html containers are .

:root {
  /*========== Colors ==========*/
  /*Color mode HSL(hue, saturation, lightness)*/
  --line-color: hsl(234, 12%, 35%);
  --active-color: hsl(234, 100%, 98%);
  --inactive-color: hsl(234, 20%, 68%);
  --body-color: hsl(189, 49%, 87%);
  --background-colour: hsl(189, 84%, 14%);
}

* {
  box-sizing: border-box;
}

body {
  height: 100vh;
  margin: 0;
  display: grid;
  place-items: center;
  background-color: var(--body-color);
}

.toggle__content {
  display: grid;
  row-gap: 1.5rem;
}

.toggle__label {
  cursor: pointer;
  padding-block: .5rem;
}

.toggle__check {
  display: none;
}

.toggle__rail {
  position: relative;
  width: 52px;
  height: 4px;
  background-color: var(--line-color);
  border-radius: 2rem;
}

.toggle__circle {
  display: block;
  width: 24px;
  height: 24px;
  background-color: var(--body-color);
  box-shadow: inset 0 0 0 4px var(--inactive-color);
  border-radius: 50%;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  margin: auto 0;
  transition: transform .4s, box-shadow .4s;
  z-index: 2;
}

.toggle__border {
  position: absolute;
  width: 32px;
  height: 32px;
  background-color: var(--body-color);
  border-radius: 50%;
  left: -4px;
  top: 0;
  bottom: 0;
  margin: auto 0;
  transition: transform .4s;
}


/* Toggle animation effects */

.toggle__check:checked~.toggle__rail .toggle__circle {
  transform: translateX(28px);
  box-shadow: inset 0 0 0 12px var(--active-color);
}

.toggle__check:checked~.toggle__rail .toggle__border {
  transform: translateX(28px);
}
<div class="toggle__content">
  <label class="toggle__label">
        <input type="checkbox" class="toggle__check">

        <div class="toggle__rail">
            <span class="toggle__circle"></span>
            <span class="toggle__border"></span>
        </div>
    </label>
</div>

I want to change it from –body-color: hsl(189, 84%, 14%) to –background-colour: hsl(189, 84%, 14%) when the switch is toggled

2

Answers


  1. The best practice in this case is using the Add/Remove class with JS, the background color that will be applied is the one added by the class, due to the specificity rule on CSS.

    First add this class to your CSS:

    .bg-color {
       background-color: var(--background-color);
    }
    

    Then add this code on the script tag, it basically waits for the DOM to be loaded then add the specified class when the checkbox is checked and remove if it’s not:

        document.addEventListener('DOMContentLoaded', () => {
            let checkbox = document.getElementsByClassName('toggle__check')[0];
            checkbox.addEventListener('change', () => {
                if (checkbox.checked) {
                    // Add the class when checkbox is selected
                    document.body.classList.add('bg-color');
                } else {
                    // Remove the class when checkbox is not selected
                    document.body.classList.remove('bg-color');
                }
            });
        });
    

    If you want the opposite, just change the .add and .remove positions

    Login or Signup to reply.
  2. The easiest change is to simply listen for the input (or change if you prefer) event, and then toggle a class on the <body> element based on the checked/unchecked state of the <input> as below, with explanatory comments in the code:

    // here we use document.querySelector() to get the first element on the page that
    // matches the supplied CSS selector; note that if you have multiple matching
    // elements you'll need to use document.querySelectorAll(), and then use a loop of
    // some kind to bind an event to each element (also this should also have been stated
    // in your question):
    document.querySelector('.toggle__check')
      // we then use EventTarget.addEventListener() to bind the anonymous Arrow function
      // as the event-handler of the 'input' event fired on the element:
      .addEventListener('input',
        // here we're using an Arrow function, as we have no requirement to use "this",
        // and we pass in a reference to the Event Object (here called "evt", but that's
        // a user-defined name, you can call it what you prefer) passed from the
        // EventTarget.addEventListener() method:
        // within the function body:
          //  we find the <body> element (via document.body):
        (evt) => document.body
          // we utilise the Element.classList API:
          .classList
          // calling the toggle() method, and supply a class-name to add, or remove,
          // if the evaluation is true (or truthy) the class-name is added, and if
          // false (or falsey) it's removed.
          // within the assessment we retrieve the Event.currentTarget property-value
          // which returns the element to which the function was bound (the <input>)
          // and the 'checked' property of that Element returns a Boolean value,
          // true if it's checked and false if it's not checked:
          .toggle('alt-color', true === evt.currentTarget.checked));
    :root {
      /*========== Colors ==========*/
      /*Color mode HSL(hue, saturation, lightness)*/
      
      /* purely as an aside, I've changed your color syntax to use
         CSS Colors Level 4 syntax, in which the original
         "hsl(234, 12%, 35%) can be written as a space-separated
         list of values hsl(<hue> <saturation> <lightness>), and may
         include opacity: hsl(<hue> <saturation> <lightness> / <alpha>)
         without having to specify hsla(); while I've deliberately
         added the 'deg' unit to the initial value, that's implied if
         the unit is absent and not necessary to specify; but it is
         a personal preference of my own. */
      --line-color: hsl(234deg 12% 35%);
      --active-color: hsl(234deg 100% 98%);
      --inactive-color: hsl(234deg 20% 68%);
      --body-color: hsl(189deg 49% 87%);
      --background-colour: hsl(189deg 84% 14%);
    }
    
    * {
      box-sizing: border-box;
    }
    
    body {
      height: 100vh;
      margin: 0;
      display: grid;
      place-items: center;
      background-color: var(--body-color);
      /* here we add a transition, in order that the background-color
         transitions between different colour-values: */
      transition: background-color 300ms linear;
    }
    
    /* here we specify a different background-color for the
       <body> element if it has the class-name of 'alt-color': */
    body.alt-color {
      /* as an aside, I strongly suggest that you use the same
         spelling of "colour" throughout your CSS; it's up to
         you how you spell it (color, colour, or even kolour)
         would all be perfectly valid but switching between
         spellings (above you have '--body-color' and here you
         have '--background-colour') increases the likelihood
         of unexpected errors/failures: */
      background-color: var(--background-colour);
    }
    
    .toggle__content {
      display: grid;
      row-gap: 1.5rem;
    }
    
    .toggle__label {
      cursor: pointer;
      padding-block: .5rem;
    }
    
    .toggle__check {
      display: none;
    }
    
    .toggle__rail {
      position: relative;
      width: 52px;
      height: 4px;
      background-color: var(--line-color);
      border-radius: 2rem;
    }
    
    .toggle__circle {
      display: block;
      width: 24px;
      height: 24px;
      background-color: var(--body-color);
      box-shadow: inset 0 0 0 4px var(--inactive-color);
      border-radius: 50%;
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      margin: auto 0;
      transition: transform .4s, box-shadow .4s;
      z-index: 2;
    }
    
    .toggle__border {
      position: absolute;
      width: 32px;
      height: 32px;
      background-color: var(--body-color);
      border-radius: 50%;
      left: -4px;
      top: 0;
      bottom: 0;
      margin: auto 0;
      transition: transform .4s;
    }
    
    
    /* Toggle animation effects */
    
    .toggle__check:checked~.toggle__rail .toggle__circle {
      transform: translateX(28px);
      box-shadow: inset 0 0 0 12px var(--active-color);
    }
    
    .toggle__check:checked~.toggle__rail .toggle__border {
      transform: translateX(28px);
    }
    <div class="toggle__content">
      <label class="toggle__label">
            <input type="checkbox" class="toggle__check">
    
            <div class="toggle__rail">
                <span class="toggle__circle"></span>
                <span class="toggle__border"></span>
            </div>
        </label>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search