skip to Main Content

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

Answers


  1. 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>
    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search