Home > OS >  How would I add a CSS background when my switch is toggled/checked in JavaScript?
How would I add a CSS background when my switch is toggled/checked in JavaScript?

Time:03-24

document.addEventListener('DOMContentLoaded', function () { var checkbox = document.querySelector('input[type="checkbox"]'); var RainbowBackground = ` .Rainbow { height: 100%; width: 100%; left:0; right: 0; top: 0; bottom: 0; position: absolute; background: linear-gradient(#ff0000, #ff4000, #ff8000, #ffbf00, #ffff00, #bfff00, #80ff00, #40ff00, #00ff00, #00ff40, #00ff80, #00ffbf, #00ffff, #00bfff, #0080ff, #0040ff, #0000ff, #4000ff, #8000ff, #bf00ff, #ff00ff, #ff00bf, #ff0080, #ff0040, #ff0000); background-size: 10000% 10000%; -webkit-animation: rainbow 3s ease infinite; animation: rainbow 3s ease infinite;}

    @keyframes rainbow { 
        0%{background-position:0% 82%}
        25%{background-position: 50% 9.5%}
        50%{background-position:100% 19%}
        75%{background-position: 75% 41%}
        100%{background-position:0% 82%}
    }
    `
var styleSheet = document.createElement("RainbowBackground")
styleSheet.innerText = RainbowBackground
document.head.appendChild(styleSheet)

checkbox.addEventListener('change', function () { if (checkbox.checked) {

    document.getElementById('body2').add = 'styleSheets'
    document.getElementById('text').innerHTML = 'ON';
} 
else {
  
    document.getElementById('body2').style.background = 'none'
    document.getElementById('text').innerHTML = 'OFF';
}

}); });

CodePudding user response:

Use element.classList.toggle to toggle a class from JavaScript.

const checkBox = document.getElementById("checkbox")
const card = document.getElementById("card")

checkbox.addEventListener("change", () => {
    card.classList.toggle("bg_color")
})
.card{
  height: 100px;
  width: 100px;
  background: red;
}

.bg_color{
  background: linear-gradient(#ff0000, #ff4000, #ff8000, #ffbf00, #ffff00, #bfff00, #80ff00, #40ff00, #00ff00, #00ff40, #00ff80, #00ffbf, #00ffff, #00bfff, #0080ff, #0040ff, #0000ff, #4000ff, #8000ff, #bf00ff, #ff00ff, #ff00bf, #ff0080, #ff0040, #ff0000);
}
<div id="card" >
  
</div>
<input type="checkbox" id="checkbox">

  • Related