Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When somebody clicks a I want sound to be played

Tags:

javascript

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">
like image 916
badrijani Avatar asked Jan 27 '23 00:01

badrijani


2 Answers

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.

like image 50
Quentin Avatar answered Feb 09 '23 04:02

Quentin


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.

like image 45
CodeIt Avatar answered Feb 09 '23 05:02

CodeIt