Im making a piano app using vanilla JS and have it so the piano keys can be clicked using the keyboard.
So that whenever certain keys are pressed on the keyboard, the corresponding button will be pressed.
But i also want the button click css effect to activate.
I managed to make the keyboard keys work using the .click() method, but this doesn’t activate the button click css effect. Is there a way to do that?
this is what i have so far.
document.addEventListener('keydown', (event) => {
if (event.repeat) return
switch (event.key) {
case "a":
document.getElementById("c4").click();
break
// then a bunch more cases for the rest of the keys
>Solution :
You can do
const a = document.getElementById("c4")
document.addEventListener('keydown', (event) => {
switch (event.key)
case "a":
a.click();
a.classList.add("down")
and remove the class on keyUp
To save you some time, perhaps you can use this codepen I took over to add JS to it
https://codepen.io/mplungjan/pen/dyjLKYJ
I added keyboard events to it, but the :active pseudo class is not triggered on click.