'Play audio on image hover in HTML (multiple images)
This is my first attempt at audio in HTML. So I have a grid of images that have an overlay of text on them, and I want the audio to play a different sound on hover over each image. I got the audio to play but it seems to play the SAME audio file on all images. Can someone help me understand why?
Thank you!
<section class="full_width four_col_grid">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div2">
<div class="container">
<img class="image" src=" https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg" >
<div class="overlay">När det farliga avfallet och allt som kan materialåtervinnas sorterats ut finns det ofta en rest kvar - soppåsen.
Men den kan också återvinnas!</div>
<audio id="audio">
<source src="https://css-tricks.com/examples/SoundOnHover/audio/beep.ogg" type="audio/ogg">
</audio>
</div>
<script>
var audio = $("#audio")[0];
$("#div2").mouseenter(function() {
audio.play();
audio.loop = true;
});
$("#div2").mouseleave(function() {
audio.pause();
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div2">
<div class="container">
<img class="image" src=" https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg" >
<div class="overlay">När det farliga avfallet och allt som kan materialåtervinnas sorterats ut finns det ofta en rest kvar - soppåsen.
Men den kan också återvinnas!</div>
<audio id="audio">
<source src="http://www.ringelkater.de/Sounds/2geraeusche_gegenst/papier_knuellen.wav" type="audio/x-wav">
</audio>
</div>
<script>
var audio = $("#audio")[0];
$("#div2").mouseenter(function() {
audio.play();
audio.loop = true;
});
$("#div2").mouseleave(function() {
audio.pause();
});
</script>
</section>
</main>
Solution 1:[1]
Steps:
please remove all script that you have added and add my given script
replace id attribute of audio tag and place class attribute
$(document).ready(function() { $(".image").mouseenter(function() { var audio = this.parentElement.getElementsByClassName("audio")[0]; audio.play(); audio.loop = true; }); $(".image").mouseleave(function() { var audio = this.parentElement.getElementsByClassName("audio")[0]; audio.pause(); }); })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ehsan |