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

JavaScript background color change function does not interact with the html button

this is my first time using StackOverflow, so I still don’t know how to use the code snippets properly.

I am still a beginner into programming and chose to start with the front-end side, i’ve done an orange background with "this is the red heading" written in red, it worked.

however, I’m trying to make a button that when it’s clicked, only the background color changes from orange to yellow, but the button doesn’t do anything at all.

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

here’s the code("estilo" is the name of the CSS file and "responsividade" is the name of the JS file):

function changeColor() {
  document.getElementById("redhead").style.backgroundColor = "yellowbg";
}
#redhead {
  background-color: orange;
  color: red;
  padding: 40px;
  text-align: center;
}

#yellowbg {
  background-color: yellow;
  padding: 40px;
  text-align: center;
}
<!DOCTYPE html>
<html>

<head>

  <body>

    <link rel="stylesheet" href="estilo.css">

    <script src="responsividade.js"></script>

    <h1 id="redhead">this is the red heading</h1>


    <button type="button" onclick="changeColor()">Click Here</button>

  </body>
</head>

</html>

>Solution :

Here: document.getElementById("redhead").style.backgroundColor = "yellow"; you are trying to assign a css class name to the backgroun color property.

function changeColor() {
  document.getElementById("redhead").style.backgroundColor = "yellow";
}
#redhead {
  background-color: orange;
  color: red;
  padding: 40px;
  text-align: center;
}

#yellowbg {
  background-color: yellow;
  padding: 40px;
  text-align: center;
}
<!DOCTYPE html>
<html>

<head> </head>

  <body>

    <link rel="stylesheet" href="estilo.css">

    <script src="responsividade.js"></script>

    <h1 id="redhead">this is the red heading</h1>


    <button type="button" onclick="changeColor()">Click Here</button>

  </body>


</html>
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