How can I play a sound file when the onload event fires using JavaScript?
For example:If I have a webpage, when a user clicks on a button and this will pop-up a window. While the pop-up window is loading, the page will play a sound file.
Add a HTML5 audio element into your document:
<audio id="foobar" src="yoursample.ogg" preload="auto">
Set it hidden via CSS:
#foobar { display: none }
On the any JavaScript event handler play the audio:
var sample = document.getElementById("foobar");
sample.play();
For more information
https://developer.mozilla.org/en-US/docs/Using_HTML5_audio_and_video
Depending on your web application purpose you might want to support old browsers:
http://www.misfitgeek.com/play-sound-in-html5-and-cross-browser-support-with-backward-compatability/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With