skip to Main Content

I have an HTML with a video element with 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 error in the console, and the video just doesn’t play.
I can’t figure out what can possibly be wrong.
The video plays perfectly when I add the controls attribute in the video tag, but my aim is to not use browsers controls and to build my own controls.

Here is a sample of my code. I used this random video here just so the source is valid.
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>

2

Answers


  1. The problem with the code is that when the video.play method is supplied as an event listener function, it loses its context and fails. The problem can be resolved by enclosing 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();
    });
     <video width="320" height="180">
        <source src="https://mdn.github.io/learning-area/javascript/apis/video-audio/finished/video/sintel-short.mp4" type="video/mp4"></video>
        <button>Play</button>
    Login or Signup to reply.
  2. Change your eventListener’s listener to:

    playButton.addEventListener("click", () => video.play());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search