I'm currently working on an interactive music app that mimics the functionality of a piano. Users are able to click on different boxes on the screen, triggering a unique musical note to play.
While I initially considered manually collecting all the Ids for both the boxes and audio files, I believe there must be a simpler and more efficient approach.
An initial attempt at looping through the box elements and extracting their Ids was successful, but I encountered difficulties in retrieving the corresponding audio file names. One potential solution I thought of involved matching the box Ids with the name attribute values of the audio files, although I haven't been able to implement this yet.
Below is a snippet of the code structure:
<div id="main">
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<div id="box3" class="box"></div>
<div id="box4" class="box"></div>
<div id="box5" class="box"></div>
<div id="box6" class="box"></div>
<div id="box7" class="box"></div>
</div>
<audio id="box1_sound" name= "notes" >
<source src="audio/d_note.mp3" type="audio/mp3"></source>
</audio>
Javascript Operations:
var box1 = document.getElementById('box1');
var box1Note = document.getElementById('box1_sound');
box1.addEventListener('mousedown', function() {
box1Note.currentTime = 0;
box1Note.play();
});
var boxName = document.getElementsByClassName('box');
var notes = document.getElementsByName('notes');
for (var j = 0; j < notes.length; j++) {
var notesVal = notes[j].name;
console.log(notesVal);
}
for (var i = 0; i < boxName.length; i++) {
boxName[i].addEventListener('mousedown', function() {
var boxId = this.id;
console.log(boxId);
});
}
Your assistance in solving this challenge would be greatly appreciated. Thank you!