Solution 1 :

It’s in your html – your missing the “c4”

change

<audio id="C" ><source src="notes/C4.mp3"></audio>

to

<audio id="C4" ><source src="notes/C4.mp3"></audio>

Problem :

I’ve made piano based on yt tutorial but I have some issue that I can’t fix…
When I click using mouse/keyboard on first button it doesn’t work, others are working just fine. Do you know where the error is in this code?

const WHITE_KEYS = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']
const BLACK_KEYS = ['2', '3', '5', '6', '7', '9', '0']

const keys = document.querySelectorAll('.key')
const whiteKeys = document.querySelectorAll('.key.white')
const blackKeys = document.querySelectorAll('.key.black')

keys.forEach(key => {
  key.addEventListener('click', () => playNote(key))
})

document.addEventListener('keydown', e => {
  if (e.repeat) return
  const key = e.key
  const whiteKeyIndex = WHITE_KEYS.indexOf(key)
  const blackKeyIndex = BLACK_KEYS.indexOf(key)

  if (whiteKeyIndex > -2) playNote(whiteKeys[whiteKeyIndex])
  if (blackKeyIndex > -1) playNote(blackKeys[blackKeyIndex])
})

function playNote(key) {
  const noteAudio = document.getElementById(key.dataset.note)
  noteAudio.currentTime = 0
  noteAudio.play()
  key.classList.add('active')
  noteAudio.addEventListener('ended', () => {
    key.classList.remove('active')
  })
}

download code

jsfiddle link

Comments

Comment posted by volt

Your first key has no

Comment posted by minimal working example within the question itself

You should provide a

Comment posted by Smokie

Thank you sir, I was 100% its js issue, I didn’t even check html

By