I have a sound file that I would like him to be heard only if a certain image on my page is loaded.
how can I manage that?
what do I need to add to document ready?
I have a sound file that I would like him to be heard only if a certain image on my page is loaded.
how can I manage that?
what do I need to add to document ready?
Include the ImagesLoaded()
plugin.
HTML
<audio id="my_sound">
<source src="horse.mp3" type="audio/mpeg">
<source src="horse.ogg" type="audio/ogg">
Your browser does not support this audio format.
</audio>
jQuery
var audio = document.getElementById('my_sound');
$('img#my_image').imagesLoaded(function(e) {
audio.play();
});
HTML:
<img class="alertSound" src="img.jpg" />
<audio id="imgLoadedSound" src="loaded.ogg">
Your browser does not support the <code>audio</code> element.
</audio>
JS:
$('img.alertSound').load(function(){
$('#imgLoadedSound').get(0).play();
});
Or better: JsBin demo
$(function() {
function imgIsLoaded() {
var audio = new Audio('loaded.ogg');
var img = new Image().src = this;
img.onload = function(){
audio.play();
};
}
$('img.alertSound').each(function() {
if( this.complete ) {
imgIsLoaded.call( this );
} else {
$(this).one('load', imgIsLoaded);
}
});
});