UNPKG

@alecefe/platzimediaplayer

Version:

An implementation of a MediaPlayer through the Professional Javascript Course

48 lines (34 loc) 1.26 kB
import MediaPlayer from "../MediaPlayer"; class AutoPause { private threshold: number; player: MediaPlayer; constructor(){ this.threshold = 0.25; this.handlerIntersection = this.handlerIntersection.bind(this); this.handlerVisibilityChange = this.handlerVisibilityChange.bind(this); } run(player: MediaPlayer){ this.player = player; const observer = new IntersectionObserver(this.handlerIntersection, {threshold : this.threshold}) observer.observe(this.player.media) document.addEventListener("visibilitychange", this.handlerVisibilityChange) } private handlerVisibilityChange(){ const isVisible = document.visibilityState === 'visible' if(isVisible){ this.player.play(); } else { this.player.pause(); } } private handlerIntersection(entries: IntersectionObserverEntry[]) { const entry = entries[0]; const isVisible = entry.intersectionRatio >= this.threshold; if( isVisible ){ this.player.play(); } else { this.player.pause(); } } } export default AutoPause;