Search code examples
javascripthtml5-videoarrow-keys

Native video player: Remove event handlers from key presses


I'm building a web based video playing platform and need full control over the replay behaviour of video tags. Specifically, I want to implement my own scrubbing function. For that I want to disable the native behaviour to skip through the replay of video tags in focus by pressing "arrow left", "arrow right" and "space" and make my own keyboard control.

I have implemented a global keystroke function to be able to control the video player from anywhere:

window.addEventListener('keyup', this.keyboardControl);

To stop the video player in focus to react to keypresses on its own, I've tried to overwrite the handlers like this:

let video = document.getElementById('video');
video.addEventListener("keydown", function(event){
  event.preventDefault();
});
video.addEventListener("keypress", function(event){
  event.preventDefault();
});
video.addEventListener("keyup", function(event){
  event.preventDefault();
});

To remove the event listeners with target.removeEventListener(type, listener[, options]);, I'd need to know the name of the native function which is executed and I think varies from browser to browser.

Is there a way? Thanks bunches!

EDIT: I'm using the attribute "controls" in my video tag. If I would remove it, it works but also looses the GUI controls, which I need. Also, happens in all the broswers i can test (Chrome, FF, Safari).


Solution

  • You've gotta bite the bullet, ditch the controls attribute and make your own custom controls. That portion is really not all that much code, but if you want a pretty GUI to replace it that may take a little googling or MS Painting.

    https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/cross_browser_video_player

    https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/Video_player_styling_basics

    You're trying to do something akin to what Youtube and Vimeo do, so go check out their video players for inspiration. Try not to glaze over at how complicated they are, just basically understand it's all JS, HTML, and CSS. They made the buttons, scrubbers, "like," "share," and all of that themselves.

    Bonus is that your player will look the same in all browsers.

    If you want to phone it in, there's open source ones out there:

    https://blog.bitsrc.io/5-open-source-html5-video-players-for-2018-38fa85932afb