skip to Main Content

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

Answers


  1. 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)
    
    Login or Signup to reply.
  2. simply:

    document.addEventListener('keydown', evt =>
      {
      if (evt.key == 'c') 
        {
        if (evt.cntrlkey)
          document.getElementById('low-c#').play();
        else
          document.getElementById('low-c').play();
        }
      });
    
    Login or Signup to reply.
  3. 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();
      }
    });
    
    Login or Signup to reply.
  4. 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();
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search