Search code examples
javascriptaddeventlistenerplyr.js

Can't trigger ended event with Plyr.js


I'm trying to implement https://github.com/sampotts/plyr#events but cannot trigger the ended state with the embeds using the addEventListener() method as I'm not using jquery. I'm currently trying to just simply display a msg when it's over. but it doesn't even get displayed on console.

I have created the element and exposed it to public using this code

document.addEventListener('DOMContentLoaded', () => { 
  // == Plyr JS ==
  const player = new Plyr('#player', {
    autoplay: false,
  }); 
  // Expose
  window.player = player;

});

I'm already loading new sources using the player.source within the public code.

Tried to call the event state using this. But I can't even get the log on console.

player.addEventListener('ended', () => {
  console.log(`Video is finished`)
});

Solution

  • I've included the line where I wait for the DOM to load and it worked.

    document.addEventListener('DOMContentLoaded', () => {
     const player = new Plyr('#player', {
      // player options
      }); 
    
     player.on('ended', event => {
        // functions that I'd like to add
      });
    

    Turns out the .on function mentioned on the documentary wasn't jQuery's .on() and it works just as fine .addEventListener if I kept it within the DOMContentLoaded