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