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">
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With