Rhys Edwards Rhys Edwards - 1 month ago 8
Javascript Question

Pause button not working on background video

Im trying to create a nice background video that has some text on top as well as a button that i can use to pause and unpause the video, the video works fine and loops, but i cant pause the video.

<html>

<head>
<script src="js/script.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="css/custom.css">
</head>

<body>
<video poster="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/polina.jpg" id="bgvid" playsinline autoplay muted loop>
<source src="dudleyByDrone.mp4" type="video/mp4">
</video>
<div id="polina">
<h1>dudley</h1>
<p>Directed by joe bloggs
<p><a href="">original article</a>
<p>blah blah</p>
<button>Pause</button>
</div>
</body>

</html>


js (I got this code from here and though it says "// only functional if "loop" is removed" i have tried removing "loop" and it still doesn't pause:

var vid = document.getElementById("bgvid");
var pauseButton = document.querySelector("#polina button");

function vidFade() {
vid.classList.add("stopfade");
}

vid.addEventListener('ended', function()
{
// only functional if "loop" is removed
vid.pause();
// to capture IE10
vidFade();
});
pauseButton.addEventListener("click", function() {
vid.classList.toggle("stopfade");
if (vid.paused) {
vid.play();
pauseButton.innerHTML = "Pause";
} else {
vid.pause();
pauseButton.innerHTML = "Paused";
}
})

Answer

You need to reference the button with more specificity.

 var playPause = document.querySelector("#playPause");

There are changes throughout the source playButton changed to playPause which is not the problem only a preference. An indirect selector may or may not work well with document.querySelector() since it tends to accept simple selectors more readily (from experience, not sure if it's documented.)

SNIPPET

var vid = document.getElementById("bgvid");
var playPause = document.querySelector("#playPause");

function vidFade() {
  vid.classList.add("stopfade");
}

vid.addEventListener('ended', function() {
  // only functional if "loop" is removed 
  vid.pause();
  // to capture IE10
  vidFade();
});
playPause.addEventListener("click", function() {

  if (vid.paused) {
    vid.play();
    playPause.innerHTML = "Pause";
  } else {
    vid.pause();
    playPause.innerHTML = "Paused";
  }
})
<html>

<head>
  <script src="js/script.js" type="text/javascript" charset="utf-8"></script>
  <link rel="stylesheet" href="css/custom.css">
</head>

<body>
  <video poster="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/polina.jpg" id="bgvid" playsinline autoplay muted loop>
    <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
  </video>
  <div id="polina">
    <h1>dudley</h1>
    <p>Directed by joe bloggs
      <p><a href="">original article</a>
        <p>blah blah</p>
        <button id="playPause">Play/Pause</button>
  </div>
</body>

</html>