Search code examples
javascripthtmlbackgroundkeypresskeyboard-events

How do i change the background when a certain key is pressed?


How do I change the html background in different colors when someone types 1-8 in a html input WITHOUT pressing enter?

for example pressing 1 makes the html background green, pressing 2 makes it red etc.


Solution

  • You need to bind the keydown event to a function that will change the background-color style property depending on the pressed keyCode:

    window.addEventListener('keydown', event => {
      switch (event.keyCode) {
          case 49: // 1
            setBackgroundColor('red');
            break;
          case 50: // 2
            setBackgroundColor('green');
            break;
          case 51: // 3
            setBackgroundColor('blue');
            break;
          case 52: // 4
            setBackgroundColor('yellow');
            break;
          case 53: // 5
            setBackgroundColor('black');
            break;
          case 54: // 6
            setBackgroundColor('white');
            break;
          case 55: // 7
            setBackgroundColor('purple');
            break;
          case 56: // 8
            setBackgroundColor('#333');
      }
    });
    
    function setBackgroundColor(color) {
        document
          .querySelector('body')
          .style
          .backgroundColor = color;
    }
    

    Here's a working sample: https://codepen.io/anon/pen/zpMEyQ

    Key code reference table: https://css-tricks.com/snippets/javascript/javascript-keycodes/