Aljosa Aljosa - 2 months ago 14
HTML Question

Interactive video (3-in-1)

I have just been asked to direct a video for a local band. They want a video that can be ''directed'' by the person who is viewing it. They want to do a similar project to this one: http://media.columbiarecords.com/jackwhite/

So the idea is that a viewer can switch between multiple videos. I have tought about overlaying videos and then just bringing them to front by pressing a certain button. I had found this html on internet:

<div id="video" style="width: 1280px; height: 720px; overflow: hidden">
<video src="DSC_0189.MOV" style="width: 100%; height: 100%;"></video>
<video src="DSC_0190.MOV" style="width: 100%; height: 100%;"></video>
</div>


and the .js

var video = document.getElementById('video');
function switchVideo(n) {
var x, y,
n = n % 6; //0 <= n <= 5
x = n % 3;
y = Math.floor(n / 3);
//todo: don't forget to copy for vendor prefixed versions of 'transform'
video.style.transform = 'translate(' + (-1280 * x) + 'px, ' + (-720 * y) + 'px)';
}
//todo: call switchVideo from the appropriate buttons


I know it a huge Q but i have been up for the last two days, trying to find the answer, but my basic code skills are too weak for this. I guess I shouldn't say yes to the projects before checking if I am able to complete them. :D

Thank you!

Answer

You can set <video> element position to absolute, use Promise.all() to wait for each video canplaythrough event to fire before calling .play() on both videos. Use keydown and keyup events to toggle display:none, display:block of the videos.

var videos = document.querySelectorAll("video");
var promises = Promise.all(Array.from(videos).map(function(video) {
    return new Promise(function(resolve, reject) {
      video.addEventListener("canplaythrough", resolve);
      video.addEventListener("error", reject);
    })
  }))
  .then(function() {
    videos.forEach(function(video) {
      video.play();
    });
    videos[0].style.display = "none";
    document.addEventListener("keydown", function(e) {
      var key = e.key;
      if (key === "b" || key === "3") {
        videos[1].style.display = "none";
        videos[0].style.display = "block";
      }
    });
    document.addEventListener("keyup", function(e) {
      videos[1].style.display = "block";
      videos[0].style.display = "none";
    });
    window.focus();
  })
  .catch(function(err) {
    console.log(err);
  });
video {
  position: absolute;
  left: 20vw;
}
Press <b>B</b> or <b>3</b> to toggle videos
<video width="320px" height="240px" src="http://nickdesaulniers.github.io/netfix/demo/frag_bunny.mp4"></video><video width="320px" height="240px" src="http://mirrors.creativecommons.org/movingimages/webm/ScienceCommonsJesseDylan_240p.webm"></video>