P
P
prolina2019-09-13 17:29:20
YouTube
prolina, 2019-09-13 17:29:20

Play YouTube video only when scrolled to it?

It is necessary to implement video playback only when scrolled to it (Angular 2+). The project uses youtube api

<section class="al-video-section">
  <div class="al-video-wrapper">
    <div class="al-video-wrapper-overlay">
      <div  id="player" style="margin-top: -400px; border: none"></div>
    </div>
  </div>
</section>

import {AfterViewInit, Component, OnInit} from '@angular/core';

declare global {
  interface Window {
    YT: {
      Player(id: string, options: object): void,
    };

    onYouTubeIframeAPIReady?(): void;
  }
}

@Component({
  selector: 'al-video-section',
  templateUrl: './video-section.component.html',
  styleUrls: ['./video-section.component.less'],
})
export class VideoSectionComponent implements OnInit, AfterViewInit {
  public player: HTMLIFrameElement;
  constructor() {
  }

  // tslint:disable-next-line:no-any
  public onPlayerReady(event: any): void {
    event.target.playVideo();
  }

  // tslint:disable-next-line:no-any
  public onPlayerStateChange(event: any): void {
    if (event.target.getPlayerState() === 0) {
      event.target.seekTo(3, false);
    }
  }
  public ngAfterViewInit(): void {
    const playerApiScript: HTMLScriptElement = document.createElement('script');
    playerApiScript.type = 'text/javascript';
    playerApiScript.src = 'https://www.youtube.com/iframe_api';
    document.body.appendChild(playerApiScript);
  }

  public ngOnInit(): void {
    window.onYouTubeIframeAPIReady = () => {
      this.player = new window.YT.Player('player', {
        videoId: 'videoID',
        height: '1300px',
        width: '100%',
        events: {
          onReady: event => {
            if (window.pageYOffset >=
              event.target.a.parentNode.offsetParent.offsetTop - 200) {
              this.onPlayerReady(event);
            }
          },
          onStateChange: event => {
            this.onPlayerStateChange(event);
          },
        },
        playerVars: {
          controls: 0,
          modestbranding: 1,
          rel: 0,
          showInfo: 0,
          mute: 1,
          loop: 1,
          playlist: 'videoID',
          enablejsapi: 1,
        },
      });
    };
  }
}

Now the video is played only if, when refreshing the page, you immediately go down to where the video is located.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2019-09-13
@dollar

Video autoplay is evil .
Let the user decide when to start browsing.
The "Play" button will suffice.

spoiler
Это не является ответом на вопрос формально. Но зато является реальным ответом на вопрос по существу. Ведь вряд ли автор хочет отпугивать пользователей агрессивной подачей контента, понижать конверсии и т.д. А если действительно хочет, то, пожалуй, лучше отдельно это объяснить в вопросе.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question