I am building a webpage with the spanish alphabet framed in a grid and I want the user to hear how the letters sound whenever they click on them.
There are 27 divs (for each letter) and 27 variables (each are assigned an audio file) therefore I want to connect them somehow.
This is the HTML code (part of it):
<div class="grid-item" id="a">A</div>
<div class="grid-item" id="b">B</div>
<div class="grid-item" id="c">C</div>
<div class="grid-item" id="d">D</div>
This is the JS code (part of it):
const a = new Audio('a.mp3');
const b = new Audio('b.mp3');
const c = new Audio('c.mp3');
const d = new Audio('d.mp3');
How can I build a function that will enable the user to hear the audio file when they click on the div?
I tried to build an array of the variables then loop them along with the ID’s but it failed.
2
Answers
You can create an array of the audio variables and assign a click event listener to each div element in the grid:
JSFiddle with sample audio.
Thanks for the question. I have an option here that uses onclick to reference a javascript object to select and play a sound based on the div’s id.
HTML:
JS: