MarUSPT MarUSPT - 1 year ago 57
HTML Question

Block sound in HTML page when it loads

I need some help because tthe chat sound when the user writes is being played when i refresh/load the page.

I need to know if it's possible make it not play only when the page is loaded.

Code in Context

var audioElement5 = document.createElement('audio');
audioElement5.setAttribute('src', 'sounds/chat.wav');

If i place the file where the code is script.js in the head section this plays the sound, if i place it above the place where I'm creating the sounds they will play one when the user writes something but when i load the page i get these following errors:

uncaught referenceerror audioElement5 is not defined (anonymous function)

So the solution that i need is to not play the sound when the html is loading or something similar to that.

I also tested like this:

beforemy body i set this:


audioElement5.muted = true;

and above my footer this:


audioElement5.muted = false;

but didn't work.

Answer Source

You should move your code to windows onload function, so it will trigger only when page is loaded....

windows.onload = function(){
  // move your code here


you can place your code in a function like:

function loadAudio(){
   // your code

and call it before /body


Hope this helps?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download