I have four images. When I mouseover them, I want each one of them to play a different sound. Well, I did that, but created different variables for each and also different functions. And in the HTML I have the container with the images and then in another <div>
the audio.
I create a new variable that selects all images and loops over them:
var roll = document.querySelectorAll("img");
for (var i=0; i<roll.length; i++){
roll[i].addEventListener("mouseover",function(){
console.log(this);
this.audio.play();
})
}
But then even that the "this" is the image it says: Cannot read property 'play' of undefined
. And I getting confusing of how I connect the sound with the image.
The html looks like this:
<div class="container">
<div class="down music"><img id="batman" src="#"></div>
<div class="up music"><img id="bane" src="#"></div>
<div class="down music"><img id="batman" src="#"></div>
<div class="up music"><img id="batman" src="#"></div>
</div>
<audio id="batman" src="sounds/batman.wav"></audio>
<audio id="bane" src="sounds/ceremony.mp3"></audio>
<audio id="joker" src="sounds/free.wav"></audio>
<audio id="alfred" src="sounds/mud.wav"></audio>
Your issue is this
is referring to each <img>
tag, and not the audio sources. Here is a working codepen that onMouseOver
alerts the corresponding div's value. (I did not have access to audio sources but should be relatively easy to switch over). The following should work for audio tags, granted I did not test this.
HTML:
<div class="container">
<div class="down music"><img id="monkey" src="https://images.pexels.com/photos/145947/pexels-photo-145947.jpeg?auto=compress&cs=tinysrgb&h=350" height="90"></div>
<div class="up music"><img id="dog" src="https://boygeniusreport.files.wordpress.com/2016/11/puppy-dog.jpg?quality=98&strip=all&w=782" height="90"></div>
<div class="down music"><img id="cat" src="https://www.bluecross.org.uk/sites/default/files/styles/thumbnail_pet/public/pets/149194.jpg?itok=xZLl3maM" height="90"></div>
<div class="up music"><img id="cow" src="https://boygeniusreport.files.wordpress.com/2016/11/puppy-dog.jpg?quality=98&strip=all&w=782" height="90"></div>
</div>
<audio id="audiomonkey" src="#">monkey</audio>
<audio id="audiodog" src="#">dog</audio>
<audio id="audiocat" src="#">cat</audio>
<audio id="audiocow" src="#">cow</audio>
JavaScript:
var roll = document.querySelectorAll("img");
for (var i=0; i<roll.length; i++){
roll[i].addEventListener("mouseover",function(){
var idOfImg = this.id; //gets each id of the img
document.getElementById("audio" + idOfImg).play(); //gets your right sound, based off id
});
}
We get each id of the image by this.id
and then get the corresponding element with audio in front of ID, and then just use the .play()
method.