Answer the question
In order to leave comments, you need to log in
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,
},
});
};
}
}
Answer the question
In order to leave comments, you need to log in
Video autoplay is evil .
Let the user decide when to start browsing.
The "Play" button will suffice.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question