Aljosa Aljosa - 1 year ago 79
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:

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>

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' = '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 Source

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) {;
    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";
  .catch(function(err) {
video {
  position: absolute;
  left: 20vw;
Press <b>B</b> or <b>3</b> to toggle videos
<video width="320px" height="240px" src=""></video><video width="320px" height="240px" src=""></video>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download