-1

I am trying to get the hex code to show up in the background color changer I made. Can I use document.getElementById? Here is my code. I want the Hex code to display when I press the Change Color button? Would I use an array to do this or what would be the best option to use? I trying, to just get better at JS I am really struggling with this so any help would be helpful.

function bcc() {
  const color = document.getElementById('changeColor');
  color.style.color = newColor;
}
body {
  margin: 0;
  padding: 0;
  background-color: rgb(219, 219, 161);
}

h1,
h2 {
  text-align: center;
}

#button {
  text-align: center;
  margin: 0 0 0 45em;
}
<h1>Background Color Changer</h1>
<h2>RGB Color: </h2>
<br>
<p id="changeColor">
  <button onclick="bcc()">Click to change color</button>
</p>
Daweed
  • 1,419
  • 1
  • 9
  • 24

2 Answers2

2

First, add an ID to the element where you want to display the color, like so:

<h2 id="color">RGB Color: </h2>

Then, change your JS function to this:

function bcc() {

  const color = document.getElementById('color');
  const backgroundColor = window.getComputedStyle(document.body ,null).getPropertyValue('background-color');

  color.innerHTML = "RGB Color: " + backgroundColor;

}

This will give you: RGB Color: rgb(219, 219, 161)

Dozatron
  • 1,056
  • 9
  • 7
-1

I think what you meant to change is the backgroundColor attribute. color is the color of the text not of the background. You also want to put the id attribute on your button if that is the background you want to change. I don't think you need need the <p> anchor around your button. I tried to find a solution to your problem below

function bcc() {

    const color = document.getElementById('changeColor');

    color.style.backgroundColor = 'black';

}
body {
    margin: 0;
    padding: 0;
    background-color: rgb(219, 219, 161);
}

h1,
h2 {
    text-align: center;
}

#button {
    text-align: center;
    margin: 0 0 0 45em;
}
<!DOCTYPE html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Background Color Changer</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="background.css">
</head>

<html>
<body>

    <h1>Background Color Changer</h1>
    <h2>RGB Color: </h2>

    <br>
    <p>
        <button id="changeColor" onclick="bcc()">Click to change color</button>
    </p>
</body>

</html>
clanglai
  • 149
  • 1
  • 6