mwah
mwah

Reputation: 23

I can't add event listener to a object

i am trying to make a music player in javascript and encountered a problem. Every time i run the code it shows this error at the last three lines of code. Error: index.js:12 Uncaught TypeError: Cannot read property 'addEventListener' of null at index.js:12

can anyone help me to debug this thing?

document.querySelector(".play-button").addEventListener("click", function (){
  document.querySelector(".play-button").classList.add("fa-pause")
   document.querySelector(".play-button").classList.remove("fa-play")

   var icare= new Audio("songs/i don't care.mp3")
   icare.play();

})

document.querySelector("fa-pause").addEventListener ("click", function(){
  icare.pause()
})

Upvotes: 0

Views: 1123

Answers (1)

raina77ow
raina77ow

Reputation: 106385

Even with typo fixed, the code's still in trouble. See, this line...

document.querySelector('.fa-pause').addEventListener ("click", /* ... */)

... is not able to "predict" the future modifications of DOM and set up listeners for those. What happens instead is querySelector finds nothing (as there's no element with fa-pause class yet), returns null, then you have a TypeError thrown.

Still, even if it worked right, you'd still have an issue, as it's the same element - .play-button - listening for both 'play' events and 'pause' events.

One possible workaround here is using just a single event listener, doing different things depending on element's state. But even that's not all: icare variable should be external to event listener, otherwise it won't be persisted.

Here's how it call can be solved (I've changed the audio url for obvious reasons):

const icare = new Audio(
  'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3');
document.querySelector(".play-button").addEventListener("click",
  function() {
    const playButton = this;
    const playButtonClassList = playButton.classList;
    if (playButtonClassList.contains('fa-play')) { // ... handle play
      icare.play();
    } else { // ... already playing, handle pause
      icare.pause();
    }
    playButtonClassList.toggle('fa-play');
    playButtonClassList.toggle('fa-pause');
  });
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet" />
<i class="play-button fa fa-play" aria-hidden="true"></i>

Upvotes: 2

Related Questions