Use 2 keycodes to return event

72 Views Asked by At

I'm 3 weeks into learning JS, and am working on a project to build a playable piano. When typing the letter c, it will play the note c. That part is working fine, but now I want the user to hold the control key and type c to make it play a different note, c#. How would i set this up? Below is what I've tried working on, but I can't get this to work.

Any refactoring advice is also helpful - I'm going to have a lot more keys played

document.addEventListener('keydown', (playNote) =>{

    if(playNote.key == 'c'){
        document.getElementById('low-c').play();    
            }
 
    if(playNote.key == 'c' && playNote.cntrlkey == true){
        document.getElementById('low-c#').play();
            }
    }
4

There are 4 best solutions below

0
aabdulahad On

Check this page for keyboard events.
You will find a value for if the ctrl key is pressed under playNote.ctrlKey
Then do

if(playNote.key == 'c' && playNote.ctrlKey)
2
Mister Jojo On

simply:

document.addEventListener('keydown', evt =>
  {
  if (evt.key == 'c') 
    {
    if (evt.ctrlKey)
      document.getElementById('low-c#').play();
    else
      document.getElementById('low-c').play();
    }
  });
1
Ali Nauman On

You are close. As the other answer mentions, the property you want to read is ctrlKey, not cntrlkey. Another problem is a logical one - you need to check for the ctrl key press before checking for just c press, and it also needs to be with an if else. Otherwise, both c and c# will be played on pressing ctrl+c.

document.addEventListener("keydown", (event) => {
  if (event.key === "c" && event.ctrlKey == true) {
    document.getElementById("low-c#").play();
  } else if (event.key === "c") {
    document.getElementById("low-c").play();
  }
});
0
XMehdi01 On

This code plays different piano notes when you press the c key, and whether it's combined with the Ctrl key or not. If you press Ctrl + c, it plays low-c#; if you press just c, it plays low-c.

document.addEventListener('keydown', (playNote) => {
    if (playNote.key === 'c' && playNote.ctrlKey) {
        document.getElementById('low-c#').play();
    } else if (playNote.key === 'c') {
        document.getElementById('low-c').play();
    }
});