Reputation: 3
I'm creating a page which has 5 button elements in the html document call boton and I want them to sound when I click on them. But it doesn't work.
This is the javascript code
const rollSound = new Audio("./sounds/button-click-off-click.mp3");
document.getElementsByClassName('boton').addEventListener("click", e => rollSound.play());
And the HTML
<ul class="barra">
<li><a href="#fotos" class="boton">Galería</a></li>
<li><a href="https://docs.djangoproject.com/en/2.2/ref/templates/builtins/" class="boton" onmousedown="audio.play()">Sesiones/Horarios</a></li>
<li><a href="#video" class="boton" onmousedown="audio.play()">Artículos</a></li>
<li><a href="https://docs.djangoproject.com/en/2.2/ref/templates/builtins/" class="boton" onmousedown="audio.play()">Información personal</a></li>
<li><a href="https://docs.djangoproject.com/en/2.2/ref/templates/builtins/" class="boton" onmousedown="audio.play()">Redes Sociales</a></li>
</ul>
Upvotes: 0
Views: 58
Reputation: 916
You can write it like this to make it sound. Different key sequences can be combined into a wonderful piano song. And here is a great reference for your piano work, I hope you enjoy it😁
Piano: https://github.com/Wscats/piano
Demo: https://wscats.github.io/piano/build
const audios = [
new Audio('https://wscats.github.io/piano/build/samples/piano/a84.mp3'),
new Audio('https://wscats.github.io/piano/build/samples/piano/a89.mp3'),
new Audio('https://wscats.github.io/piano/build/samples/piano/a85.mp3'),
new Audio('https://wscats.github.io/piano/build/samples/piano/a73.mp3'),
new Audio('https://wscats.github.io/piano/build/samples/piano/a79.mp3'),
new Audio('https://wscats.github.io/piano/build/samples/piano/a80.mp3'),
new Audio('https://wscats.github.io/piano/build/samples/piano/a65.mp3'),
];
let i = 0;
let body = document.body;
for (; i < audios.length; i++) {
let button = document.createElement('button');
button.innerText = i;
const audio = audios[i];
button.addEventListener('click', () => {
audio.play();
});
body.appendChild(button);
}
Upvotes: 1
Reputation: 13399
The problem is that you have a list of elements on which you try to attach an event listener.
The getElementsByClassName method returns an array like object with DOM elements.
So, if you want each item to have the event attached, you have to loop through all of them and add listeners separately.
Something like this:
const rollSound = new Audio("./sounds/button-click-off-click.mp3");
const elements = document.querySelectorAll('.boton');
elements.forEach(el => el.addEventListener('click', () => {
rollSound.play();
}));
Upvotes: 1