Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign CSS to a background via JavaScript

This is my first time trying to change my html background by pressing a button. I’ve a CSS which I teste in the body tage by doing and that worked. However, when I used a JavaSript function to change the background only when the button is pushed, the code doesn’t run.

This is my CSS:

.chiefs{
background: #E31837;
background: -moz-linear-gradient(-45deg, #E31837 0%, #FFFFFF 50%, #FFB612 100%);
background: -webkit-linear-gradient(-45deg, #E31837 0%, #FFFFFF 50%, #FFB612 100%);
background: linear-gradient(135deg, #E31837 0%, #FFFFFF 50%, #FFB612 100%);
}

This is my HTML with an internal JavaScript:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<main>
<button onClick="myFunc()" id="game">Chiefs</button>
</main>

<script> 
function myFunc(){
    document.body.style.backgroundColor = "chiefs";
}

</script>

I’m unsure what to put in the script section after I define myFunc.

I tried multiple different definitions and functions but they only worked for a solid color. For example, with a button I could change the background color to green by just typing ‘green’ but since I have a gradient CSS, I don’t know what to do.

>Solution :

Use .classList.add() instead, since chiefs is a CSS class, not a color.

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

.chiefs{
background: #E31837;
background: -moz-linear-gradient(-45deg, #E31837 0%, #FFFFFF 50%, #FFB612 100%);
background: -webkit-linear-gradient(-45deg, #E31837 0%, #FFFFFF 50%, #FFB612 100%);
background: linear-gradient(135deg, #E31837 0%, #FFFFFF 50%, #FFB612 100%);
}
This is my HTML with an internal JavaScript:
<main>
<button onClick="myFunc()" id="game">Chiefs</button>
</main>

<script> 
function myFunc(){
    document.body.classList.add("chiefs");
}

</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading