Javascript DOM HTML Audio Object create and set autoplay property

Introduction

Create a <video> element and setting the autoplay property.

Click the buttons to create a AUDIO element.

One with autoplay set to true, and one with autoplay set to false.

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction(true)">Audio with autoplay</button>
<button onclick="myFunction(false)">Audio without autoplay</button>
<br>

<script>
function myFunction(p) {
  var x = document.createElement("AUDIO");
  x.setAttribute("id", "myVideo");
  x.setAttribute("controls", "controls");
  
  var y = document.createElement("SOURCE");
  y.setAttribute("src", "sound.ogg");
  y.setAttribute("type", "audio/ogg");
  x.appendChild(y);/*w w  w.  j  av a2 s  . c  o  m*/
  
  var z = document.createElement("SOURCE");
  z.setAttribute("src", "sound.mp3");
  z.setAttribute("type", "audio/mpeg");
  x.appendChild(z);

  // Set the autoplay property:
  x.autoplay = p;

  document.body.appendChild(x);
}
</script>
</body>
</html>



PreviousNext

Related