4

When I click key A, I want my sound to be played but it doesn't seem to work

var key1 = new Audio();
key1.src = "sounds/316898__jaz-the-man-2__do.wav";

var x = document.getElementById("first");
x.addEventListener("keyup", function(event) {
  if (event.keyCode == 65) {
    event.preventDefault();
    key1.play();
  }
})
#first {
  width: 100px;
  height: 100px;
}
<img id="first" src="https://www.mathpages.com/home/piano2.gif">
adiga
  • 34,372
  • 9
  • 61
  • 83
badrijani
  • 127
  • 9

2 Answers2

5

Images are not designed to be interactive controls. They cannot (by default) have the focus. They can't have children either.

This means that it cannot be in focus or be the ancestor of the element that is in focus at the time you press A.

Attach the event handler to something which can be in focus (or the ancestor of such) such as an <input> or the document.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

I tried attaching the EventListener to the window instead of the element and it works!

var key1 = new Audio();
key1.src = "https://freesound.org/data/previews/316/316913_5385832-lq.mp3";

var x = window; 
x.addEventListener("keyup", function(event) {
  if (event.keyCode == 65) {
    event.preventDefault();
    key1.play();
  }
})
#first {
  width: 100px;
  height: 100px;
}
<img id="first" src="https://www.mathpages.com/home/piano2.gif">

You can also try attaching the listener to document or document.body and it will also work. If you want to attach it to some other elements you can refer this question.

CodeIt
  • 3,492
  • 3
  • 26
  • 37