Just a simple problem.
I want to assign a HTMLMediaElement method to variable.
// html part
<video id="player" ... />
// js part
const video = document.querySelector('#player')
const play = video.play
video.play() // works!
play() // error!
Uncaught (in promise) TypeError: Failed to execute 'play' on 'HTMLMediaElement': Illegal invocation
anyone knows why this error happened?
The native DOM implementation of HTMLMediaElement.play requires this to be bound to an HTMLMediaElement.
video.play() works because the this value is bound to video.
play() doesn't work because the this value is now bound to something else (maybe window?).
You can either call it using:
const video = document.querySelector('#video');
play = video.play;
play.call(video);
<video id="video" src="http://vjs.zencdn.net/v/oceans.mp4" controls>
or "save it for later" using bind:
const video = document.querySelector('#video');
play = video.play.bind(video);
play();
<video id="video" src="http://vjs.zencdn.net/v/oceans.mp4" controls>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With