I want to make a button that changes the background of the page. I wrote in js but I don’t know why it doesn’t work

Asked

Viewed 30 times

-1

<!doctype html>
<html>
    <head>
        <title>ABC</title>
        <meta charset="utf-8">
        <script type="text/javascript">
            function changebgtoblue(){
                document.getElementById('bla').style.background-color="blue";
            }
        </script>
        <style>
            #bblue{
                background-color:blue;
            }
        </style>
    </head>
    <body id="bla" /*style="background-color:#000;"*/>
            <button id="bblue" onclick="changebgtoblue()">blue</button>
    </body>
</html>

1 answer

1

3 things wrong with your code:

  • In HTML you cannot comment attributes, remove this /* */
  • The estate background-color in Javascript can not have -, must be written in camelCase, that is to say: backgroundColor
  • puts the script at the end of body, or uses onload to run the script. Your Javascript code does not yet know the presence of the HTML code because it has not yet been read.

Corrected example:

#bblue {
  background-color: lightblue;
  padding: 10px;
}
<body id="bla">
  <button id="bblue" onclick="changebgtoblue()">blue</button>

  <script type="text/javascript">
    function changebgtoblue() {
      document.getElementById('bla').style.backgroundColor = "darkblue";
    }
  </script>
</body>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.