birdyoung
birdyoung

Reputation: 207

Uncaught TypeError: Cannot read property 'play' of null at playVid

I'm getting errors for play and pause.. both saying "Uncaught TypeError: Cannot read property 'play' of null at playVid"

My code below, I'm not sure what I'm doing wrong.

<button onclick="playVid()"  type="button">Play Video</button>
<button onclick="pauseVid()" type="button">Pause Video</button><br> 

<video id="myVideo" width="320" height="176">
  <source src="<?php echo $video ?>" type="video/mp4">
</video>

var vid = document.getElementById("myVideo");

function playVid() {
  vid.play();
}

function pauseVid() {
  vid.pause();
}

function menuAnimate(x) {
  $(".menu-wrap").toggleClass("open");
}

Upvotes: 1

Views: 3862

Answers (1)

Lovesh Dongre
Lovesh Dongre

Reputation: 1344

Always run the script after all the HTML elements are loaded

What happens when you run the script first

var vid = document.getElementById("myVideo");

Since the body of the element is not loaded, there exists no element which has an id myVideo and vid is initialised to null

Now when you click on the button playVid() is called but fails to execute vid.play() since vid is initialised to null

<!DOCTYPE html>
<html lang="en">
<head>
 <title>Document</title>
</head>
<body>
  
  <button onclick="playVid()"  type="button">Play Video</button>
  <button onclick="pauseVid()" type="button">Pause Video</button><br> 

  <video id="myVideo" width="320" height="176">
    <source src="<?php echo $video ?>" type="video/mp4">
  </video>

  <script>
    var vid = document.getElementById("myVideo");

    function playVid() {
      vid.play();
    }

    function pauseVid() {
      vid.pause();
    }

    function menuAnimate(x) {
      $(".menu-wrap").toggleClass("open");
    }
  </script>

</body>
</html>

Upvotes: 1

Related Questions