Search code examples
javascriptyoutubeembedplyrplyr.js

How to get Plyr current instance when initialized for many videos


I'm using Plyr in my webpage to play Youtube embeds in that. In my page I've about 10 videos/embeds, & my current setup like the following:

HTML

<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID1"></div>
<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID2"></div>
<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID3"></div>
<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID4"></div>
<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID5"></div>
<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID6"></div>
<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID7"></div>
<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID8"></div>
<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID9"></div>
<div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID10"></div>

JS

const players = Plyr.setup('.plyr', options);

now If I play video #3 on the page how can I get that instance so that I can control the player & listen to that instances events so that I can do something else with those.

The documentation only talks about single instance when instantiating only one player

const player = new Plyr('#player', options);

but I instantiated multiple at once...


Solution

  • what you should do is to add your variable to data-plyr-config like this

    <div class="plyr" data-plyr-provider="youtube" data-plyr-embed-id="videoID10" data-plyr-config='{ "the_id": "YOUR ID" }'></div>
    

    then in your Js code you can get the variable

    const plyr = Plyr.setup('. plyr', config);
        plyr.forEach(function (instance) {
            instance.on('playing', function () {
                console.log(instance.config.the_id);
            });
        });
    
    • where 'the_id' is the key that you just created
    • Note: The key name can be anything