Play audio onHover with jQuery
The simplest way to play audio files in your page without the need of flash is the usage of HTML5 tag <audio> as follow:
<audio autoplay="autoplay" controls="controls" loop="loop" preload="preload">
<source src="beep.ogg" type="audio/ogg">
<source src="beep.mp3" type="audio/mpeg">Your Browser doesn't support audio
</audio>
For our example we only need the attributes “autoplay” and the two tags “source” to define the url of the audio files. Just like this:
<audio autoplay="autoplay">
<source src="beep.ogg" type="audio/ogg">
<source src="beep.mp3" type="audio/mpeg">
</audio>
Now we let jQuery take over by embedding the html code for all <a> tags whenever onMouseOver is done:
$(document).ready(function(){
var audioFileName = "beep";
var mp3File = audioFileName + ".mp3";
var oggFile = audioFileName + ".ogg";
$('body').append('<div id="audio" style="position:absolute; top:-200px;"></div>');
$('a').hover(function(){
$('#audio').html('<audio autoplay="autoplay">'+
'<source src="' + oggFile + '" type="audio/ogg">'+
'<source src="' + mp3File + '" type="audio/mpeg"></audio>');
},
function(){ });
});
Thats it!
DEMO: Check the upper menu of this page to hear how it works
Useful Links: