I want jQuery to play a sound when an animation starts
I have elements on my page that animate in and when they do I would like each of them to have their own sound. The animation is as follows, this includes the targetBeep sound.
targetBeep = new Audio('22540839_interface-alarm-03_by_umcsound_preview.mp3');
$("#top-left").delay(1000).animate({"opacity": "1"}, 1).animate({"color": "#FFFFFF"},100).animate({"color": "#323035"},100).animate({"color": "#FFFFFF"},100).animate({"color": "#323035"},100);
I would like the beep when it animates from #FFFFFF
to #323035
. I tried putting targetBeep.play();
in the animation code but it didn't work.
Solution 1:
Provided you're using at least jQuery v1.8, you can use the start
or complete
options in .animate() (depending on exactly when you want the sound to play)
$("#top-left")
.delay(1000)
.animate({"opacity": "1"}, 1)
.animate({"color": "#FFFFFF"}, {
duration: 100,
start: () => {
targetBeep.play()
}
})
.animate({"color": "#323035"}, 100)
.animate({"color": "#FFFFFF"}, 100)
.animate({"color": "#323035"}, 100);