-4

I want the typeColor input value to update the background color of the box. I want the typeName input value to update the text on the box. Instead, the color doesn't change at all and the name just disappears. I've tried various solutions.

box = document.getElementById("box");
typeColor = document.getElementById("typeColor").value;
typeName = document.getElementById("typeName").value;
boxName = document.getElementById("boxName");

function changeBoxColor() {
  box.style.backgroundColor = typeColor;
}

function changeBoxName() {
  boxName.innerText = typeName;
}
body {
  margin: 0px;
}

#box {
  width: 100px;
  height: 100px;
  background-color: grey;
  margin-left: 100px;
  margin-top: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}
<head>
  <title>test</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <input id="typeColor" placeholder="Type a color...">
  <button onclick="changeBoxColor()">Change Box Color</button>
  <input id="typeName" placeholder="Type a name...">
  <button onclick="changeBoxName()">Change Box Name</button>

  <div id="box">
    <center>
      <p id="boxName">Box</p>
    </center>
  </div>
  <script src="script.js"></script>
</body>
isherwood
  • 58,414
  • 16
  • 114
  • 157
sewqq
  • 9
  • 2
  • 2
    you need to get the value of your input, the moment you press the button. You are doing it only once on page load when the input is empty – Chris G Apr 18 '23 at 12:45
  • 1
    You should also get in the habit of declaring your variables properly (see [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) and [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)). – Andy Apr 18 '23 at 12:47
  • Zero values don't have units in CSS. Also, use [event listeners](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events) rather than inline JavaScript. – isherwood Apr 18 '23 at 12:48
  • 2
    It is the SAME exact issue as your other question!!!!! https://stackoverflow.com/questions/76037837/how-do-i-find-the-value-of-an-input – epascarello Apr 18 '23 at 12:49

1 Answers1

1

The input values only get loaded when you load the file, if you want them to update you would have to place them inside the function.

let box = document.getElementById("box");
let boxName = document.getElementById("boxName");

function changeBoxColor() {
  let typeColor = document.getElementById("typeColor").value;
  box.style.backgroundColor = typeColor;
}

function changeBoxName() {
  let typeName = document.getElementById("typeName").value;
  boxName.innerText = typeName;
}
Sten
  • 45
  • 6