Q:

Trigger animation on checked radio and checkbox buttons

I would like to animate the changing of body background color when radio or checkbox button is selected.
I know how to it for a single input:
JavaScript:
const apples = document.querySelector("#apples")

apples.addEventListener("change", function() {
  if(this.checked) {
    document.body.style.animation = "switch 1s ease-in-out"
  }     
})

And then in CSS:
@keyframes switch {
  to {
    background: red
  }
}

HTML:
<form>
  <fieldset>
    <label><input type="checkbox" name="foo" id="apples">Apples</label>
    <label><input type="checkbox" name="foo" id="bananas">Bananas</label>
  </fieldset>
  <fieldset>
    <label><input type="radio" name="bar" id="juice">Juice</label>
    <label><input type="radio" name="bar" id="lemonade">Lemonade</label>
  </fieldset>
</form>

But how can I do it with vanilla JavaScript if I have an object with colors paired to an id of an input?
const accentColors = {
  apples: "red",
  bananas: "yellow",
  juice: "green",
  lemonade: "yellow"
}

A:

I'm not sure that this is the best practice, but I've read that one way to create dynamic @keyframes is by injecting dynamic css that is created using js.

    const accentColors = {
      apples: "red",
      bananas: "yellow",
      juice: "green",
      lemonade: "yellow"
    }
    
    let keyFrameStylesToInject = '';
    
    // Create the styles and add event listeners
    Object.keys(accentColors).forEach(k => {
     keyFrameStylesToInject += `@keyframes switch-${k} {to {background: ${accentColors[k]}}}`;
     
     document.querySelector(`#${k}`).addEventListener('change', function(){
         if(this.checked) { 
               document.body.style.animation = `switch-${k} 1s ease-in-out`;
            }
            else {
               document.body.style.animation = undefined;
            }
     });
    });
    
    // Inject the css
    const style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = keyFrameStylesToInject;
    document.head.appendChild(style);
<form>
  <fieldset>
    <label><input type="checkbox" name="foo" id="apples">Apples</label>
    <label><input type="checkbox" name="foo" id="bananas">Bananas</label>
  </fieldset>
  <fieldset>
    <label><input type="radio" name="bar" id="juice">Juice</label>
    <label><input type="radio" name="bar" id="lemonade">Lemonade</label>
  </fieldset>
</form>

