Friday, June 8, 2012

Changing video on mouse click for video tag in HTML5

hi,
I wanted to have TV kind of facility where I can chose video and on click of selected video, the video should display in designated area.Below is the snippet for creating TV.To achieve this, complete video tag must be re-written dynamically where value of source need to be set on every click. In below snippet test is the function invoked on mouse click within canvas

      function test(e) {

           var xPos = parseInt(e.offsetX);
           var yPos = parseInt(e.offsetY);
           DeleteNode();
           createNode();
           var viSource = document.getElementById("mySrc");
           if ((xPos>0 && xPos <136))
             if((yPos>50 && yPos<201))
             {
              viSource.src = "VideoTutorial/WindowsBlogWin8CPDemo_med_ch9.mp4";
              viSource.type = "video/MP4";
              //alert("value inside video tag::" + document.getElementById("videoDiv").innerHTML);
           }
     if ((xPos > 0 && xPos < 136))
               if ((yPos > 200 && yPos < 351)) {
                   viSource.src = "VideoTutorial/863_WinAzureForWin8Nick.mp4";
                  viSource.type = "video/MP4";
                  //alert("value inside video tag::" + document.getElementById("videoDiv").innerHTML);

               }

       }

 function DeleteNode() {
           var vDiv = document.getElementById("videoDiv");
           var videoElements = document.getElementsByTagName("video");
           if (videoElements.length > 0) {
               vDiv.removeChild(document.getElementById("myvideo"));
           }
           //alert("Div Element after deleting existing video node: "+vDiv.innerHTML);

          }

       function createNode() {
             var vDiv = document.getElementById("videoDiv");
             var videoElements = document.getElementsByTagName("video");
             if (videoElements.length == 0) {
                 var vVideo = document.createElement("video")
                 vVideo.id = "myvideo";
                vVideo.setAttribute("width", "400px");
                 vVideo.setAttribute("height", "300px");
                 vVideo.setAttribute("autoplay", "autoplay");
                 vVideo.setAttribute("controls", "controls");
                 vDiv.appendChild(vVideo);
                 var source = document.createElement("source")
                 source.id = "mySrc";
                 vVideo.appendChild(source);

             }
            //alert("Div element after creating video node: "+vDiv.innerHTML);

           }

          And the output will look like -

Enjoy