I have an HTML with a video element, no controls and a button to play the video. But when I try to play the video using the button it doesn't do anything.
I don't get any errors in the console and the video doesn't play.
I can't figure out what could be wrong.
When I add the control attribute in the video tag, the video plays perfectly, but my goal is not to use browser controls and build my own.
This is my code sample. I've used this random video here so that the source works.
I hope someone can help. Thanks in advance.
const video = document.querySelector('video'); const playButton = document.querySelector('button'); playButton.addEventListener('click', video.play);
<video> <source src="https://mdn.github.io/learning-area/javascript/apis/video-audio/finished/video/sintel-short.mp4" type="video/mp4"></video> <button>Play</button>
Change the
listener
of eventListener to:The problem with the code is that when the video.play method is provided as an event listener function, it loses context and fails. This problem can be solved by encapsulating the method in an anonymous function. Please check the playButton.addEventListener(){...} function below: