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
Check this page for keyboard events.
You will find a value for if the ctrl key is pressed under
playNote.ctrlKey
Then do
simply:
You are close. As the other answer mentions, the property you want to read is
ctrlKey
, notcntrlkey
. 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.This code plays different piano notes when you press the
c
key, and whether it’s combined with theCtrl
key or not. If you pressCtrl + c
, it playslow-c#
; if you press justc
, it playslow-c
.