MarUSPT MarUSPT - 4 months ago 9
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');
audioElement5.volume=1.0;


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:

<script>

audioElement5.muted = true;
</script>


and above my footer this:

<script>

audioElement5.muted = false;
</script>


but didn't work.

Answer

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
}

OR

you can place your code in a function like:

function loadAudio(){
   // your code
} 

and call it before /body

<script>loadAudio();</script>
</body>

Hope this helps?