I want to change the background color of an HTML document by pressing enter

I used a function that changes the background color according to the user entered a mouse click. In addition, I want that after the user enters a certain color in the input field and presses the Enter key, he should immediately change the background color of the HTML body. Please help me fix this and write the code in pure javascript.

function changeColor(){

var color = document.getElementById("color").value;
document.body.style.background = color;
}
<p>
Enter your fav colour<input type="text" id="color">

<button onclick="changeColor();" onkeypress="changeColor()";> Click </button>
</p>
Run codeHide result
+4
source share
2 answers

function changeColorWhenEnter(e) {
  if (e.keyCode == 13) {
    changeColor();
  }
}
function changeColor(){
  var color = document.getElementById("color").value;
  document.body.style.background = color;
}
<p>
  Enter your fav colour
  <input type="text" id="color" onkeypress="changeColorWhenEnter(event)";>
  <button onclick="changeColor();" > Click </button>
</p>

    
Run codeHide result
+1
source

You can add a keystroke event listener that starts only when a certain key is pressed, a working example:

function changeColor(){

var color = document.getElementById("color").value;
document.body.style.background = color;
}
document.querySelector('#color').addEventListener('keydown', function(e) {
    if (e.keyCode === 13) { // enter key
       changeColor();
    }
});
<p>
Enter your fav colour<input type="text" id="color">

<button onclick="changeColor();"> Click </button>
</p>
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1678299/


All Articles