Search code examples
jqueryaudiohoverplayback

Play sound only once Jquery


I am trying to achieve something like this, upon hovering over an image, a sound is played, and I want the sound to be only played once, means after the initial hovering, the subsequent hovers will not trigger the sound to play anymore, currently i am trying this code, but it does not work

$(document).ready(function(){

$("#bg")[0].play();

var pring = 0;

$(function(){
$('#apDiv5').hover(
 function(){$("#phone")[0].play();},
 function(){$("#phone")[0].stop();
 pring++;
 if (pring > 1) {function(){$("#phone")[0].stop();}
 }});


});

});

Solution

  • You can always add a special class to the element that played the audio and test for it already has that class:

    LIVE DEMO

    $(function(){
    
       function playOnHover(el, audioFile){      
          $(el).addClass('played');
          var sound = new Audio( audioFile );   
          sound.play();      
       }
    
       $('#apDiv5').on('mouseenter', function(){
          if(!$(this).hasClass('played')) playOnHover( this, "sound.ogg" );
       });
    
    });