I tried making character cards, that when hovered over play the character his / her voiceline (only relevant parts shown), but when I hover over a character, they play every voiceline all at once, it's probably a mistake in the javascript, but I just can't figure out how to fix it.
<ul>
<header id="play_1">
<img src="/img/characters/character.png">
<audio>
<source src="/voices/charactervoice.m4a"></source>
</audio>
</header>
</ul>
<ul>
<header id="play_2>
<img src="/img/characters/character2.png">
<audio>
<source src="/voices/charactervoice2.m4a"></source>
</audio>
</header>
</ul>
//javascript:
window.onload=function(){
for (let i = 1; i <= 2; i ){
var playHover = document.getElementById('play_' i),
audios = document.querySelectorAll('audio');
console.log(audios);
playHover.addEventListener('mouseover', function() {
[].forEach.call(audios, function(audio) {
audio.volume = 0.05;
audio.play();
});
}, false);
}
}
CodePudding user response:
It should only select the audio inside the playHover
and not all the audio which is causing all the audio to play at once when hovering a card. You can try it like this (basing on how you written your code)
window.onload=function(){
for (let i = 1; i <= 2; i ){
let playHover = document.querySelector('#play_' i),
let audio = playHover.querySelector('audio');
playHover.addEventListener('mouseover', function() {
audio.volume = 0.05;
audio.play();
}, false);
}
}
or you can code it like this so whenever you're going to add a header you won't have to edit your loop condition. (Ideally, you should place a class for each header and select that instead so if ever you are going to use the header element for another use, won't have problems with selections):
window.onload=function(){
const headers = document.querySelectorAll('header');
headers.forEach((e) => {
let audio = e.querySelector('audio');
e.addEventListener('mouseover', function() {
audio.volume = 0.05;
audio.play();
}, false);
});
}