I am trying to make it so when you hover over a dog's photo, a barking sound plays. I figured out how to do it manually, but now I am trying to automate it in a loop so the code stays clean.
I am giving the image and sound corresponding ids so that I can create a loop that adds a number to the end of 'image' and 'sound'. That way I can say on #image1.mouseenter play #sound1, and on #image2.mouseenter play #sound2. If that makes sesne
here is the jsfiddle I created. and here is the script i wrote:
var i;
for (i = 1; i<=3; i++){
var barking = $("#sound"+i)[0];
$("#image"+i).mouseenter(function(){
barking.play();});
$("#image"+i).mouseleave(function(){
barking.pause();});
}
You need a closure so the i
variable have the correct value when passed to the event handler
Below is one way, and here is a few more: JavaScript closure inside loops
for (var i = 1; i <= 3; i++) {
(function(j) {
$("#image" + j).mouseenter(function() {
$("#sound" + j)[0].play();
});
$("#image" + j).mouseleave(function() {
$("#sound" + j)[0].pause();
});
})(i);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="image1" src="https://www.rocketdogrescue.org/wp-content/uploads/2013/09/DSC_0718.png" width="400px">
<img id="image2" src="https://www.rocketdogrescue.org/wp-content/uploads/2013/09/lightening.jpg" width="400px">
<img id="image3" src="https://www.rocketdogrescue.org/wp-content/uploads/2013/09/pet-food-express.jpg" width="400px">
<audio id="sound1" preload="auto" loop="loop">
<source src="http://soundbible.com/mp3/Dogs Barking-SoundBible.com-625577590.mp3">
</audio>
<audio id="sound2" preload="auto" loop="loop">
<source src="http://soundbible.com/mp3/Dog Woof-SoundBible.com-457935112.mp3">
</audio>
<audio id="sound3" preload="auto" loop="loop">
<source src="http://soundbible.com/mp3/dog-howling-yapping-daniel_simon.mp3">
</audio>