简体   繁体   中英

How do I get an audio snippet to play when hovering over an image element?

After too many hours on YT and Google, I'm here. Thanks for taking the time to read & help. :)

I'm trying to make it so that when the mouse hovers over the image, an audio snippet plays automatically. I've tried a few different things, but this is where I stopped. Can't seem to get anything to work.

HTML file snippet

<head>
    <link rel="stylesheet" href="./stylesheet.css">
    <script type="text/javascript" src="./scripts.js"></script>
...other stuff etc etc


<div class="deviruchi" data-tooltip="no touchy!">
<audio id="devi">

    <source src="./sounds/deviruchi_idle.mp3">
    <source src="./sounds/deviruchi_idle.ogg">

</audio>

        <img src="./images/deviruchi.gif">

        </div> 

Javascript file

let deviruchi = $("#devi")[0];
$(".deviruchi").onmouseenter(function () {
    deviruchi.play();
});

Thanks again: :)

Probably because you are using jquery...(j/k, but no really)

Make sure that the audio files are present on the server, check devtools for error messages (javascript as well as.network) Also, user must first interact with the webpage (click/focus, etc) before browser will allow play media files.

 hoverMe.addEventListener("mouseenter", e => { myAudio.play().catch(er => console.error(er.message, "Now, click here and try again")); }); hoverMe.addEventListener("mouseleave", e => { myAudio.pause(); });
 <div id="hoverMe">Hover over here</div> <audio id="myAudio" src="https://sample-videos.com/audio/mp3/crowd-cheering.mp3"></audio>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM