Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Component Request - Youtube Video Player #72

Open
jonmchan opened this issue Mar 14, 2023 · 0 comments
Open

Component Request - Youtube Video Player #72

jonmchan opened this issue Mar 14, 2023 · 0 comments

Comments

@jonmchan
Copy link

jonmchan commented Mar 14, 2023

I found that a youtube video component might be useful for those interested in programmatically controlling youtube video or adding analytics.

Here's a very rough example controller I created that might be able to be used as basis for a component:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static values = {
    id: String,
    height: {type: Number, default: 315},
    width: {type: Number, default: 560}
  }
  connect() {
    this.element[this.identifier] = this;

    let tag = document.createElement('script');
    tag.src = "https://www.youtube.com/player_api";
    let firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    // Replace the 'ytplayer' element with an <iframe> and
    // YouTube player after the API code downloads.
    let player;
    window.onYouTubePlayerAPIReady = () => {
      player = new YT.Player(this.element, {
        height: this.heightValue,
        width: this.widthValue,
        videoId: this.idValue,
        events: {
          'onStateChange': this.onPlayerStateChange
        }
      });
    }

    // Should somehow expose these events in the component
    this.onPlayerStateChange = (event) => {
      if (event.data == YT.PlayerState.PLAYING ) {
        alert(`Play Promo Video at ${Math.floor(player.getCurrentTime())}`);
      }else if (event.data == YT.PlayerState.ENDED) {
        alert("Complete Promo Video")
      }
    }
  }
}

usage:

<div data-controller="youtube-video" data-youtube-video-id-value="qYIG9R7yJ1Q"></div>

NOTE: This is very rough and you can only embed a single video element with this. Being able to handle multiple videos and not rely on a single function call would probably be useful for making this more universal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant