How to change background on every button of virtual keyboard?

106 Views Asked by At

Can you help me with my virtual keyboard? I need to add keydown event with changing background into orange color on each button. in HTML I use buttons with classes .letter and .symbol.

window.addEventListener('keydown', function(event) {
    console.log('Event', event)

    if(event.keyCode) {
      myButton.style.backgroundColor = 'orange';  
    }

})

window.addEventListener('keyup', function(event){
    myButton.style.backgroundColor = 'white'
 })
1

There are 1 best solutions below

3
epascarello On

Using a data attribute you can select the button based on the key pressed.

function updateKeys(evt) {
  const btn = document.querySelector(`button[data-key="${evt.key}"]`);
  if (!btn) return;
  btn.classList.toggle('active', event.type === 'keydown');
}


window.addEventListener('keydown', updateKeys);
window.addEventListener('keyup', updateKeys);
.active {
  background-color: orange;
}
<button data-key="a">a</button>
<button data-key="s">s</button>
<button data-key="d">d</button>
<button data-key="f">f</button>