简体   繁体   中英

js code inside script tags of HTML5 work but not in external js file

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);

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM