I'm trying to build a simple piano so a keypress plays the corresponding sound. I have data attributes set up in my html and on the audio elements like so:
<div class="piano-keys">
<div data-key="65" class="wkey" id="key"></div>
<div data-key="81" class="bkey" id="key></div>
</div>
<audio id="65" data-key="65" src="notes/261-C.mp3"></audio>
<audio id="83" data-key="83" src="notes/293-D.mp3"></audio>
and my jquery is as follows:
$(document).keyup(function(e){
if(e.keyCode == 65){
var c = document.getElementById('65');
c.play();
c.currentTime = 0;
} else if(e.keyCode == 83){
var c = document.getElementById('83');
cSharp.play();
cSharp.currentTime = 0;
}
});
This obviously works but I will need 25 if/else and I know it can be done a lot cleaner. Instead of having to target the individual ID's. I tried to create variables for they key presses like this:
var key = $('.key[data-key="${e.keyCode}"]');
but that obviously never worked. I'm new to jquery if that hasn't become painfully obvious by the stage.
First of all, you can't have the same ID multiple times on one page, other than that you can just do something like this
$(document).keyup(function(e){
var key = e.which;
var note =document.getElementById(key);
note.play();
note.currentTime = 0;
})
it will play the corresponding audio to which ever key is pressed. I'm not sure what you are doing with currentTime
but you didn't mention it in your question, so this need adapting to do whatever it is that you are doing with that.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments