Search code examples
javascripthtmlvideo

HTML5 Video Focus for Input Devices


I have a page with multiple HTML5 videos. I want to utilize keyboard and mouse events to interact with each video. In Flash, that's not a problem, because once you click on the video object, that certain video will gain focus and receive all events from any input devices, unless you click out of it. I'm still new to HTML5 videos, but I am not sure as to how to mimic this focus feature in HTML5 video with javascript, since focus doesn't exist for the video tag and you can't control a single video without it.

Many thanks in advance!


Solution

  • I found a way to fake focus for a video element by utilizing a global variable. ex:

        $(function(){
            var focused_vid;
            $('video').click(function(){ focused_vid = this });
            $(document).keydown(function(e){ 
                if (focused_vid){
                    var skip_step = focused_vid.duration*.01;
    
                    switch(e.which){
                        case 37: // Back arrow
                            focused_vid.currentTime -= skip_step;
                            break;
    
                        case 39: // Forward arrow
                            focused_vid.currentTime += skip_step;
                            break;
                    }
                }
            });
        });