Displaying dynamically a video reader with Node

The methods of the Node interface of DOM allow to create a dynamic HTML (or XML) document by adding nodes to the tree.

An example can be given for viewing videos from Youtube, thanks to the plugin installed on all recent browsers.

The code to generate

A classic video player running on all browsers, has the following code:

<embed 
	width="300" height="300" 
	wmode="transparent"
	type="application/x-shockwave-flash" 
	src="https://www.youtube.com/v/WbFFs4DHWys">
</embed> 

This code has been tested with all browsers.

Generating the code

A function has been defined, which uses the appendChild and setAttribute methods of Node:

function displayVideo(url, ident)
{
  var element = document.getElementById(ident);
  var emb = document.createElement("embed");
  emb.setAttribute("type" , "application/x-shockwave-flash");
  emb.setAttribute("width", "300");
  emb.setAttribute("height", "300");
  emb.setAttribute("name", "wmode");
  emb.setAttribute("src", url);
  element.appendChild(emb);
}

- The method createElement of Document creates a Node object that you assign to emb.
- The location in the HTML page to insert the object may be found with the getElementByID method, and according to the ID given as argument.
- The object is inserted by the instruction element.appendChild(emb).
- The various properties such as width, height, type of the object are added by the method setAttribute.

The function is called dynamically with onload because it is required that the DOM tree is already built to locate the element where to insert the object.

<script type="text/javascript">
    var url = "https://www.youtube.com/v/WbFFs4DHWys";
    window.onload=function x()
    { 
      displayVideo(url, "zone");
    } 
</script>

The function is called with in parameters the URL of the video, and the name of the element where to insert it, in this case "zone".

Demonstration

The demo shows firstly the video player created dynamically, under the heading "DYNAMIC" then the same player is statically written below the title "STATIC".

DYNAMIC

STATIC

Source code of the demo:

<p>DYNAMIC</p>
<p id="zone"></p>
<p>STATIC</p>
<p>
<embed width="300" height="300" wmode="transparent"
type="application/x-shockwave-flash"
src="https://www.youtube.com/v/WbFFs4DHWys">
</embed>
</p>
<script src="node-video.js" type="text/javascript"></script>
<script type="text/javascript">
var url = "https://www.youtube.com/v/WbFFs4DHWys";
window.onload=function x() { displayVideo(url, "zone"); }
</script>

The video used for the example shows an experimental robot android, but this is the future ...

© 2008-2022 Xul.fr