Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
How would I add a CSS background when my switch is toggled/checked in JavaScript?

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';
}

}); });

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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" class="card">
  
</div>
<input type="checkbox" id="checkbox">

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!