badrijani
badrijani

Reputation: 127

When somebody clicks a I want sound to be played

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">

Upvotes: 4

Views: 62

Answers (2)

CodeIt
CodeIt

Reputation: 3618

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.

Upvotes: 3

Quentin
Quentin

Reputation: 944076

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.

Upvotes: 5

Related Questions