search

Home  >  Q&A  >  body text

How to play video using javascript?

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粉466290133P粉466290133310 days ago562

reply all(2)I'll reply

  • P粉328911308

    P粉3289113082024-02-18 13:52:10

    Change the listener of eventListener to:

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

    reply
    0
  • P粉852578075

    P粉8525780752024-02-18 00:49:14

    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();
    });
     
        

    reply
    0
  • Cancelreply