Luke
Luke

Reputation: 67

document.addEventListener not working with load event

I'm looking for an explanation as to why window.addEventListener works on the following script but not document.addEventListener. I've had a look at the MSN docs for the load event and from what I can gather it should work. Also, this stack overflow answer was useful up to a point but given my understanding of the MSN docs linked above I'm still confused. This is mainly because there is no reference to window being the only available EventTarget.

The script is part of a personal project which is to create a record player. Click a button and the song plays, click again and it pauses and so on. Nothing too fancy but it's also at the limits of my current js skill level so any advice is appreciated.

function audioPlayer(){

    // Create vars
    var audio = new Audio('https://s3-us-west-2.amazonaws.com/s.cdpn.io/336102/mpthreetest.mp3');
    var btn = document.getElementsByClassName('dial-a')[0];

    // Create event listener
    btn.addEventListener('click', playPause);

    // Play Pause function 
    function playPause(){

      // If audio paused then play on click
        if(audio.paused){
            audio.play();
       }
      // Else audio playing then pause on click
      else {
            audio.pause();
       }
    }
}

// document.addEventListener doesn't work for some reason
window.addEventListener('load', audioPlayer, false);

Upvotes: 2

Views: 2316

Answers (1)

David Gilbertson
David Gilbertson

Reputation: 4853

The Mozilla docs stating document.addEventListener('load'... were incorrect (I have updated them). That event doesn't fire in Edge, Chrome or Firefox.

The following isn't related to your question, but it might be of interest.

The window can be loaded but the audio file not available yet. You may want to use the audio element canplay event which is quite specifically targeted to what you want to do.

Upvotes: 2

Related Questions