JSFiddle - React, Tailwind, and code Playground

by sitruc

HTML

<ol>
    <li>Click in this frame so that the key listener here will find you.</li>
    <li>Use your "j" and "k" keys to cycle through videos
</ol>
<video id="vid" controls>
	<source src="http://www.808.dk/pics/video/gizmo.mp4" type="video/mp4">
</video>

CSS

video {
    width: 500px;
    height: auto;
}

JavaScript

//
// NOTES:
//
// This uses jQuery, however that is just for 
//    convenience - everything here could easily be
//    done in plain JavaScript as well if you don't
//    use jQuery. 

// This uses HTML5 video tags and
//    doesn't factor in the alternate webm and ogg 
//    formats - in production, you might want to include
//    those.
//
// Keys could be any key, of course. This just uses
//    j and k for demo purposes.
//
// These 3 videos don't share a common size or aspect
//    ratio.
//

// the videos we'll cycle through
var videos = new Array(
    "http://www.808.dk/pics/video/gizmo.mp4",
    "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",
    "http://web.cortland.edu/flteach/mm-course/webcam-vid-2_x264_192.mp4"
);

// set to 1, as we have already used the first video in the tag
var onVideo = 1;

// listen for a key up event
$(document).keyup(function (event) {
    var changeVideo = false;

    // did they press j or k?
    if (event.which == "74") {
        // j key - go back in array, or if already at
        //    end, loop around
        onVideo = ((onVideo - 1) < 0) 
                ? (videos.length - 1) : (onVideo - 1);
        changeVideo = true;
    } else if (event.which == "75") {
        // j key - go ahead in array, or if already at
        //    end, loop back to start
        onVideo = ((onVideo + 1) == videos.length) 
                ? 0 : (onVideo + 1);
        changeVideo = true;
    }  
    
    // now switch the video to our updated onVideo position
    //    they hit j or k
    if (changeVideo) {
        $("#vid").attr("src", videos[onVideo]);
        // play it automatically
        $("#vid")[0].play();
    }
});