0

Hi guys I'm trying to make a custom video player.

I'm trying to make a button pause or play the video but it is not able to do so.

Html code: index.html

<html>
<head>
  <script type="text/javascript" src="../js/jquery-3.2.1.min.js"></script>
  <script type="text/javascript" src="../js/player.js"></script>
  <link rel="stylesheet" href="../css/style.css" />
  <title></title>
</head>
<body>
  <video id="main_video" src="../media/4k.mp4" controls autoplay></video>
  <p>
  <button onclick="play_pause()" type="button">PLAY/PAUSE</button>
</body>
</html>

Javascript code: player.js

var video_screen = document.getElementById('main_video');
var play_pause_status = "play";

function play_pause()
{
  if (play_pause_status == "pause")
  {
    video_screen.play();
    play_pause_status = "play";
  }
  else
  {
    video_screen.pause();
    play_pause_status = "pause";
  }
}

When I click the button this is the error shown:

Uncaught TypeError: Cannot read property 'pause' of null at play_pause

I want to keep my Javascript code into a separate file.

I'm not able to understand the error please help.

Harpreet SINGH
  • 21
  • 1
  • 1
  • 3

2 Answers2

1

Use $(document).ready, and wrap your code inside it. You code is called before the document is ready. Or alternatively, you can get the element within the function itself as in the snippet below.

var play_pause_status = "play";

function play_pause() {
  var video_screen = document.getElementById('main_video');
  if (play_pause_status == "pause") {
    video_screen.play();
    play_pause_status = "play";
  } else {
    video_screen.pause();
    play_pause_status = "pause";
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="main_video" src="https://www.w3schools.com/html/mov_bbb.mp4" controls autoplay></video>
<p>
  <button onclick="play_pause()" type="button">PLAY/PAUSE</button>
orabis
  • 2,749
  • 2
  • 13
  • 29
0

Make sure the DOM is loaded before querying. The error you mentioned is because of video_screen.pause(). The video_screen element is null when the script is run(before the DOM is completely loaded) which could be the reason for error.

$(document).ready(function() {
  var video_screen = document.getElementById('main_video');
  var play_pause_status = "play";

  function play_pause()
  {
    if (play_pause_status == "pause")
    {
      video_screen.play();
      play_pause_status = "play";
    }
    else
    {
      video_screen.pause();
      play_pause_status = "pause";
    }
  }
});
Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36