Javascript DOM HTML Video autoplay Property set for new created <video> element

Introduction

A demonstration of how to create a <video> element and setting the autoplay property:

var x = document.createElement("VIDEO");

Click the buttons to create a VIDEO 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)">Video with autoplay</button>
<button onclick="myFunction(false)">Video without autoplay</button>
<br>

<script>
function myFunction(p) {
  var x = document.createElement("VIDEO");
  x.setAttribute("id", "myVideo");
  x.setAttribute("controls", "controls");
  var y = document.createElement("SOURCE");
  y.setAttribute("src", "video.mp4");
  y.setAttribute("type", "video/mp4");
  x.appendChild(y);/*from   w w w . j ava 2  s. c  o  m*/
  var z = document.createElement("SOURCE");
  z.setAttribute("src", "video.ogg");
  z.setAttribute("type", "video/ogg");
  x.appendChild(z);

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

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

</body>
</html>



PreviousNext

Related