4

I have used a function which changes the background color according to the user input on mouse click. Also, I want after user inputs a particular color to the input field and presses Enter key, it should change immediately the HTML body background color. Please help me to 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>
  • possible duplicate of https://stackoverflow.com/questions/12955222/how-to-trigger-html-button-when-you-press-enter-in-textbox – Silencer310 May 31 '17 at 22:32

2 Answers2

1

You can add a keypress event listener that only triggers when you hit a certain key, 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>
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
1

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>

    
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Tony Dong
  • 3,213
  • 1
  • 29
  • 32