0

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:

<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.

2
  • What are you expecting "chiefs" to do? Technically you can iterate the style sheet rules, get the value defined for .chiefs and assign that value to document.body.style.backgroundColor, see Modify element :before CSS rules programmatically in React. Commented Mar 23, 2024 at 22:07
  • You are passing class as color. That won't work. Commented Mar 23, 2024 at 22:10

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

You declared ".chiefs" as a CSS class, you can not assign it a css property. It is not a property. You should apply it to the body element instead of setting the background color property. That's why when you set solid color works, otherwise not works. Try following:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.