0

If this code is inside script tags in index.html it works fine but when moving this code to a js file referenced in the head it no longer works. One thought I had was to use window.onload but was not able to get that working. This is for a simple local HTML5 video player. It's been a while since I worked with external js. Can anyone help me out?

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

function playPause() {
  var el = document.getElementById("playButton");
  if (myVideo.paused) {
    myVideo.play();
    el.className ="";
  } else {
  
    myVideo.pause();
    el.className = "playButton";
  }
}
myVideo.addEventListener("click", playPause, false);
var pause42 = function(){
    if(this.currentTime >= 13 && !myVideo.paused) {
      this.currentTime = 42;
        this.pause();

        // remove the event listener after you paused the playback
        this.removeEventListener("timeupdate",pause42);
    }
};
myVideo.addEventListener("timeupdate", pause42);

var pause49 = function(){
    if(this.currentTime >= 45 && !myVideo.paused) {
      this.currentTime = 49;
        this.pause();

        // remove the event listener after you paused the playback
        this.removeEventListener("timeupdate",pause49);
    }
};
myVideo.addEventListener("timeupdate", pause49);
1

1 Answer 1

2

Wrap var myVideo = document.getElementById("myVideo") in a DOMContentLoaded event so the HTML element is loaded before trying to get the element in your JS file.

Then add your event listeners inside the same function as below.

document.addEventListener('DOMContentLoaded', function(){
    var myVideo = document.getElementById("myVideo");
    myVideo.addEventListener("click", playPause, false);
    myVideo.addEventListener("timeupdate", pause42);
    myVideo.addEventListener("timeupdate", pause49);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.