Using oninput event to change background body color

Viewed 72

I'm working with Javascript.

I need an input that at the same time I'm writing a color the body background change to that color. Also I need the background go white with the delete key.

<strike>
<!DOCTYPE html>
<html>
<body>

<p>Write a color for background</p>

<input type="text" id="myInput" oninput="colorForBack()">

<p id="demo"></p>

<script>
function colorForBack() {
  var x = document.getElementById("myInput").value;
  document.getElementById("demo").innerHTML = "Your color: " + x;
  element.style.backgroundColor = x;
 
}
</script>

</body>
</html>
</strike>
1 Answers
  • Don't use inline JS on* attribute handlers, same as you don't use inline style attributes. It's hard to debug and maintain. JS should be in one place only and that's your script. Use Element.addEventListener() instead.
  • Get the BODY Element using document.body or document.querySelector("body")
  • Listen for "input" and "keyup" Events. On "keyup" we can deduce the key using KeyboardEvent.key - and if matches the string "Delete" you can reset your input value accordingly
  • Don't insert unsanitized strings into your DOM! Use Node.textContent when inserting a user input string value into your document.

const EL_body = document.body;
const EL_input = document.querySelector("#myInput");
const EL_color = document.querySelector("#demo");

function setBodyBackground(ev) {
  const isDelete = ev?.key === "Delete";
  const color = isDelete ? "transparent" : EL_input.value;
  EL_color.textContent = `Your color: ${color}`;
  EL_body.style.backgroundColor = color;
  if (isDelete) EL_input.value = ""; // Reset input value on Delete key
}

["input", "keyup"].forEach(evName => EL_input.addEventListener(evName, setBodyBackground))
<p>Write a color for background</p>
<input type="text" id="myInput">
<p id="demo"></p>

Read also:

Related