Home » Tutorials Advanced Tutorial

JavaScript Popup Media Player

2.8/5.0 (42 votes total)
Rate:

Jonathan Fenocchi
February 17, 2006


Jonathan Fenocchi
Jonathan Fenocchi is a talented young developer coming at you from southern TX, USA. Accessibility advocate, proficient programmer, and determined designer, Jonathan spends his free time researching new technologies, developing new ideas, playing video games and listening to rock music. Jonathan runs a Slightly Remarkable blog where he focuses on web-related content, and continues to pursue his goals as an aspiring web developer."

Jonathan Fenocchi has written 20 tutorials for JavaScriptSearch.
View all tutorials by Jonathan Fenocchi...

Playing videos in popup windows is often a simple task, but when you end up with multiple pages for each individual video, things can quickly become complicated. In this article, we’ll be discussing how to use just one page for your popup.

It’s easy to upload a video file and open it in a new window; it’s also easy to add a description by adding an HTML page, but that’s all static – you have to edit everything, and if you want to add another video, you have to create a new HTML file. Pretty soon, you’ll have a lot of unnecessary HTML documents. We can clean that up with JavaScript, and still make it accessible to the users without JavaScript. How? Have a look at this code:

<a href=”/media/file.mpg” onclick=”popMedia(0); return false;”>Play file.</a>

The direct link is to the actual media file – users without JavaScript can download the video, however, users with JavaScript will not go to where the link specifies due to the return false statement. At this moment, the popMedia() function is undefined. To define it, put the following in the <HEAD> tags of your document.

<script type=”text/javascript”><!—
  function popMedia(id){
   window.open(“player.html?f=”+id,”_popMedia”,”width=400,height=400”);
  }
//--></script>

The next step is to open a new window and add another HTML file. By having just one media player file, we won’t have to have the same JavaScript on every page. This way, you won’t have to modify any of your HTML files to add JavaScript to the header (even if you use the SRC attribute of the SCRIPT tag, you’ll have to modify all your HTML files). You can also directly link to the player.html file instead of having it open in a new window by using the following:

<a href=”/media/file.mpg” onclick=”location.href=’player.html?f=0’; return false;”>Play file.</a>

Users without JavaScript will link directly to the file; but users with JavaScript will be taken to the player.html file. Now I’m sure you’re curious about that zero being in there, when we should be specifying a file’s location. That can easily be explained by the source code of the player.html file below:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Media Player</title>
    <script type="text/javascript"><!--
      var files = ["file1.wmv","file2.avi","file3.mov"];
      var titles = ["File 1", "File 2", "File 3" ];
      var descs = ["This is the first file.",
                "This is the second file.",
                "This is the third file, which is a Quicktime file."
                ];
      var dims = ["400x400","400x400","400x400"];
      srchStr = location.search;
      obj = document.getElementById("medObj");
      srchStr = srchStr.split("f=")[1];
      objType = files[srchStr-1].split(".")[1];
      objType = (objType=="mpg"||objType=="mpeg")?"video/mpeg":
                (objType=="avi"||objType=="wmv") ?"video/x-msvideo":"video/quicktime";
var pluginspace = (objType=="video/x-msvideo")?"http://www.microsoft.com/windows/windowsmedia/default.aspx":(objType=="video/quicktime")?"http://www.apple.com/quicktime/download/":"";
   var codebase = (objType=="video/x-msvideo")?"http://www.microsoft.com/windows/windowsmedia/default.aspx":(objType=="vide/quicktime")?"http://www.apple.com/qtactivex/qtplugin.cab":"";
      document.title += " | "+titles[srchStr-1];
      dimW = Number(dims[srchStr-1].split("x")[0]);
      dimH = Number(dims[srchStr-1].split("x")[1]);
        window.resizeTo(dimW+300, dimH+100);
        window.moveTo (10 , 10);
    //--></script>
    </head>
   <body>
       <script type="text/javascript"><!--
if(navigator.appName != "Microsoft Internet Explorer") document.write('<obj'+'ect id="medObj" pluginspace="'+pluginspace+'" codebase="'+codebase+'" data="'+files[srchStr-1]+'" standby="Loading Video..." style="float: left;" type="'+objType+'" width="'+dimW+'" height="'+dimH+'"></object>');
if(navigator.appName == "Microsoft Internet Explorer") document.write('<embed pluginspace="'+pluginspace+'" src="'+files[srchStr-1]+'" style="float: left;" type="'+objType+'" width="'+dimW+'" height="'+dimH+'"></embed>');
   --></script>
   <div id="descObj" style="float: right; width: 200px;">
    <script type="text/javascript"><!--
      document.write (descs[srchStr-1]);
    //--></script>
   </div>
  </body>
</html>

As you can see, we’re placing arrays of corresponding data in our script. This way, the zero that comes after the f refers to the first index of each array, so that the file address, title, and description all correspond to one another. We also have a fourth array called “dims.” This array is what you’ll use to specify the dimensions of your video. You’ll notice that all three of the example files – file1.wmv, file2.avi and file3.mov – have different extensions. These are for demonstration purposes. Based on the video file’s extension, the script will detect the encoding type to tell the browser what plug-in to use to interpret the file. If the browser lacks any of the plug-ins, we’ve provided URL’s where the browser can download them, so you can view the videos.

Let’s have a look at the meat of the script, and analyze it:

      <script type="text/javascript"><!—
            // The files array; when the address has f=0, it means file1.wmv
        var files = ["file1.wmv","file2.avi","file3.mov"];
            /* The titles array corresponds with the files array. When f=0, it means “File 1”; when f=1, it means “File 2” and so on. */
        var titles = ["File 1", "File 2", "File 3" ];
            // “descs,” also, corresponds with the specified file
        var descs = ["This is the first file.",
                "This is the second file.",
                "This is the third file, which is a Quicktime file."
              ];
           // “dims” is the same as files, titles, and descs.
        var dims = ["400x400","400x400","400x400"];
           /* location.search is the “?f=id” part of the current location, we’ll use this to determine the index of our arrays (files, titles, descs, dims). */
        srchStr = location.search;
           // The variable “srchStr” is just going to get what f is equal to in the URL.
        srchStr = srchStr.split("f=")[1];
           // “objType,” here, is going to figure out the file’s extension.
        objType = files[srchStr-1].split(".")[1];
           /* We’re going to do a switch-like statement here. Basically, if the file’s extension is “.mpg” or “.mpeg,” the object’s type will be “video/mpeg”; otherwise, if it’s “avi” or “wmv,” the object’s type will be “video/x-msvideo.” If it’s neither of these, it’s probably a “.mov” file, which would mean our object’s type is “video/quicktime.” If you find another file type and need to add it, you can do so by adding (objType==”new extension”)?”object type”:”default object type” in the place of the quotes at the end (the :“” part). It’s a simplified way to create many if/else statements. Whatever is in parentheses is the if – if(objType==”mpg”||objType==”mpeg”) is the same thing as (objType==”mpg”||objType==”mpeg”)?. The colon is what specifies the “else” statement. So if(ojbType==”mpg”||objType==”mpeg”){ objType = “video/mpeg”; } else { objType = “video/x-msvideo”; } means the same thing as objType = (objType==”mpg”||objType==”mpeg”)?”video/mpeg”:”video/x-msvideo”. Of course, the code we have below is more complex – it’s like an if statement inside of another if/else statement.*/
        objType = (objType=="mpg"||objType=="mpeg")?"video/mpeg":
                (objType=="avi"||objType=="wmv") ?"video/x-msvideo":"video/quicktime";
        /* Pluginspace specifies where the plug-in can be downloaded. If we don’t know what the object type is, we define the variable as an empty string. This avoids an error. Add the location of any other plug-ins, by querying their object type, if necessary. */
   var pluginspace = (objType=="video/x-msvideo")?"http://www.microsoft.com/windows/windowsmedia/default.aspx":(objType=="video/quicktime")?"http://www.apple.com/quicktime/download/":"";
        /* Codebase is the same thing as pluginspace, just for the OBJECT tag instead of the EMBED tag. Again, if we don’t know what the object type is, define the variable as an empty string. Add the location of any other plug-ins, by querying their object type, if necessary. */
   var codebase = (objType=="video/x-msvideo")?"http://www.microsoft.com/windows/windowsmedia/default.aspx":(objType=="vide/quicktime")?"http://www.apple.com/qtactivex/qtplugin.cab":"";
      /* To pretty things up a bit, we’ll add a bar and the title of the video being played to the document’s title. */
     document.title += " | "+titles[srchStr-1];
/* dimW and dimH get the dimensions of the video specified in the “dims” array */
      dimW = Number(dims[srchStr-1].split("x")[0]);
      dimH = Number(dims[srchStr-1].split("x")[1]);
    /* here we resize the window to 300 pixels wider than the video, and one hundred pixels higher than the height of the video */
        window.resizeTo(dimW+300, dimH+100);
    // let’s move the media player ten pixels from the left and top of the screen
       window.moveTo (10 , 10);
   //--></script>

You can customize the script fairly easily, but you need to change the arrays that contain the files, names, descriptions, and dimensions, respectively. You can add as many videos as you want to the array, provided all of the arrays are have the same number of elements (known as equivalence, but not equality).

Note: If the (expression)?statement:statement; code becomes too confusing, use an if/else statement instead. Now we have one last thing to cover:

      <script type="text/javascript"><!—
        /* For non-Internet Explorer users, use the W3C-recommended OBJECT tag. Basically we’re using document.write() to output the OBJECT tag with all of the values necessary: codebase, data (file SRC), type, width, height, and so on. You can modify these values – especially the style attribute – to fit your needs. */

if(navigator.appName != "Microsoft Internet Explorer") document.write('<obj'+'ect id="medObj" pluginspace="'+pluginspace+'" codebase="'+codebase+'" data="'+files[srchStr-1]+'" standby="Loading Video..." style="float: left;" type="'+objType+'" width="'+dimW+'" height="'+dimH+'"></object>');

   /* If you’re an Internet Explorer user, you need to use the EMBED tag. For some reason, Internet Explorer thinks that the OBJECT tag is a security threat and won’t play it. In contrast, a browser such as Mozilla Firefox translates the W3C-recommended OBJECT tag properly. As with the OBJECT tag above, we’re using document.write() to output the EMBED tag and its attributes. Change it as necessary. */
if(navigator.appName == "Microsoft Internet Explorer") document.write('<embed pluginspace="'+pluginspace+'" src="'+files[srchStr-1]+'" style="float: left;" type="'+objType+'" width="'+dimW+'" height="'+dimH+'"></embed>');
   --></script>
   <div id="descObj" style="float: right; width: 200px;">
      <script type="text/javascript"><!—
         /* Here we’re just outputting the description of the video currently being played. Again, you can modify the containing DIV tag to suit your needs; wherever you want to output the description, add the following line (in SCRIPT tags, of course). */
      document.write (descs[srchStr-1]);
     //--></script>
    </div>

You can change the output and customize it as much as you want.

You can download some sample files here. This is an example of the Popup Media Player in use.

Note: Since this is a video-player, no media files have been attached as they would be quite large.

Conclusion

When working with JavaScript (as in this process), there are some things consider:

1. It's always a good practice to make your JavaScript extraneous – JavaScript is not reliable in the sense that there are many users who don't know how to use it, and by relying on it you are making the content inaccessible to those individuals. The site should work without any JavaScript.

2. Beware of pop-up blockers, some which will not open pop-ups, even if you click the link. If that becomes a problem, you can link directly to the player.html file and the user can click the back button to return to the previous page instead. Remember, though, to use JavaScript to redirect to the player.html file, and set the HREF attribute’s value to the location of the media file.

3. Consider using external *.JS files instead of placing the JavaScript directly in the headers of each page. This will save file space and simplify the organization of your web site directory.

The idea of opening videos in new windows is common, but this technique should help make things easier and more manageable for you – as a webmaster – and hopefully for your end-users as well.


Add commentAdd comment (Comments: 0)  

Advertisement

Partners

Related Resources

Other Resources

arrow