0

I'm using querySelector to access a video element in HTML. I have a button to enable the webcam and begin streaming, and a second button that is disabled by default. When streaming starts, I want the second button to be enabled.

<!DOCTYPE html>
<html lang='en-US'>
  <head>
    <meta charset='UTF-8'>
    <script src='get-user-media.js'></script>
  </head>
  <body>
    <video autoplay></video>
    <div>
      <button class='button' id='get-user-media-button'>Start Camera</button>
      <button class='button' id='disabled-button' disabled>Disabled</button>
    </div>
    <script>
      document.querySelector('#get-user-media-button').addEventListener('click',onGetUserMediaButtonClick);
    </script>
  </body>
</html>

And in get-user-media.js file I have:

function onGetUserMediaButtonClick() {
  navigator.mediaDevices.getUserMedia({video: true})
  .then(mediaStream => {
    document.querySelector('video').srcObject = mediaStream;
  })
  .catch(error => console.log('Streaming error.'));
}

document.querySelector('video').addEventListener('play', function() {
  document.querySelector('#disabled-button').disabled = false;
});

Inside the onGetUserMediaButtonClick() function, querySelector('video') finds the video element and clicking the button correctly starts the stream. But the second querySelector('video') is returning null. If I paste the script into the HTML, everything works fine.

Matheus Leão
  • 417
  • 4
  • 12
  • Put `` in end of the `` – Maheer Ali Mar 19 '19 at 18:33
  • 1
    Because you've put the link to the script in your `head`, which runs before the `video` element is added to the DOM. Use an event handler like `window.addEventListener('load', () => { ... code with querySelector ... })`. – Heretic Monkey Mar 19 '19 at 18:33
  • 2
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Heretic Monkey Mar 19 '19 at 18:33
  • Thanks. This link has quite a few solutions. – Matheus Leão Mar 19 '19 at 19:14

0 Answers0