Search code examples
javascripthtmlvideohtml5-videokeyboard-shortcuts

How can you override default browser HTML5 video controls?


I'm trying to change the custom shortcuts of a video player to those of Youtube. On Youtube the arrow keys rewind and fast forward 5 seconds each. By default on Firefox and Google, when the left arrow key is pressed the video is rewound by 15 seconds, when the right arrow key is pressed the video is fast forwarded by 15 seconds. I'd like to get it to be 5 seconds. I've tried using e.preventDefault() to no avail. I have the same issue with the space bar.

Any ideas on how to make this happen?

Current Code:

window.addEventListener('keydown', function (event) {
if (event.key === "ArrowLeft") {
        event.preventDefault();
        video.currentTime -= 5;
} else if (event.key === "ArrowRight") {
        event.preventDefault();
        video.currentTime += 5;
        }
});

Thanks


Solution

  • From what is provided in OP code it looks like it should work. The only way it wouldn't is that video is null. event.key should probably be event.code. Of course that event.preventDefault() doesn't help nor hinder...or it helps in the fact if the arrow keys default behavior interfered somehow...can't really see how in your situation though.


    Demo

    window.onkeydown = vidCtrl;
    
    function vidCtrl(e) {
      const vid = document.querySelector('video');
      const key = e.code;
    
      if (key === 'ArrowLeft') {
        vid.currentTime -= 5;
        if (vid.currentTime < 0) {
          vid.pause();
          vid.currentTime = 0;
        }
      } else if (key === 'ArrowRight') {
        vid.currentTime += 5;
        if (vid.currentTime > vid.duration) {
          vid.pause();
          vid.currentTime = 0;
        }
      } else if (key === 'Space') {
        if (vid.paused || vid.ended) {
          vid.play();
        } else {
          vid.pause();
        }
      }
    }
    video {
      display: block;
      width: 320px;
      margin: 15px auto;
    }
    <video src='https://glsec.s3.amazonaws.com/mp4/60s.mp4'></video>