stamat / youtube-background

ESM / jQuery plugin for creating video backgrounds from YouTube, Vimeo or video file links.
https://stamat.github.io/youtube-background/
MIT License
173 stars 54 forks source link

How do I listen for the "video-background-play" event and other events? #51

Closed 4foot30 closed 10 months ago

4foot30 commented 1 year ago

Sorry to open this issue, but I can't seem to pick up any events being dispatched by the YoutubeBackground class, through the VideoBackgrounds class.

I'm initialising like this:

const videoBackground = new VideoBackgrounds('[data-vbs]');

And I've tried listening for the video-background-play event via various methods:

window.addEventListener('video-background-play', function(e) { alert(e) });
document.addEventListener('video-background-play', function(e) { alert(e) });
document.documentElement.addEventListener('video-background-play', function(e) { alert(e) });
const embedTargets = document.querySelectorAll('.class-name-i-added-to-the-data-vbs-elements')
if (this.embedTargets) {
    this.embedTargets.forEach((elem) => {
        elem.addEventListener('video-background-play', this.videoHasStarted);
    });
}

and so on...

I can see that the YoutubeBackground class is dispatching these events, for example: https://github.com/stamat/youtube-background/blob/master/src/youtube-background.js#L130

But I can't pick them up it seems!...

Any help much appreciated, many thanks.

avblink commented 1 year ago

Same here,

let $video = $('[data-vbg]');

$video.on('video-background-play', (e) => {
    alert('playing');
});

$video.youtube_background({ 'fit-box': true });

Nothing happens.

avblink commented 1 year ago

Can you add this line after YoutubeBackground.prototype.onVideoStateChange = function (event) {...

this.element.dispatchEvent(new CustomEvent('video-background-state', { bubbles: true, detail: {YoutubeBackground: this, videoState: event.data} }));

so it looks like this:

  YoutubeBackground.prototype.onVideoStateChange = function (event) {

    this.element.dispatchEvent(new CustomEvent('video-background-state', { bubbles: true, detail: {YoutubeBackground: this, videoState: event.data} }));

    if (event.data === 0 && this.params.loop) {
      this.seekTo(this.params['start-at']);
      this.player.playVideo();
    }
...

Then we can get any player stateChange events like this:

  let $video = $('[data-vbg]');
  $video.on('video-background-state', (e) => {
    console.log(e.detail.videoState, 'state');
  });
  $video.youtube_background({ 'fit-box': true });

Look for onStateChange event in this API doc

YouTube Player API Reference for iframe Embeds

stamat commented 10 months ago

Hey folks @avblink @4foot30, sorry for my inactivity on this project and the late replys. I've sorted out the events aligned them between the instances in the latest version v1.0.22. You can find the guide for the events as a part of the README.md.

Cheers 🥂