How to play video using javascript?
P粉466290133
P粉466290133 2024-02-17 16:44:36
0
2
554

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>

P粉466290133
P粉466290133

reply all(2)
P粉328911308

Change the listener of eventListener to:

playButton.addEventListener("click", () => video.play());
P粉852578075

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:

const video = document.querySelector('video');
const playButton = document.querySelector('button');
playButton.addEventListener('click', function() {
 video.play();
});
 
    
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template