mbio-ui
Version:
Web components library containing lightweight, ready-to-use and framework-agnostic User Interface elements.
87 lines (68 loc) • 2.09 kB
JavaScript
class MbioVideo extends HTMLElement {
static observedAttributes = ['data-video-src'];
constructor() {
super();
this.videoEle = null;
}
connectedCallback() {
this.videoEle = this.querySelector("video");
if (!this.videoEle) {
console.error("MbioVideo");
return;
}
this.addEventListener('click', this.toggleSound.bind(this));
this.addIntersectionObserver();
document.addEventListener('visibilitychange',
this.onPageVisibilityChange.bind(this));
this.setVideoSrc(this.getAttribute('data-video-src'));
}
disconnectedCallback() {
document.removeEventListener('visibilitychange',
this.onPageVisibilityChange.bind(this));
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'data-video-src' && oldValue !== newValue) {
this.setVideoSrc(newValue);
}
if (!this.getAttribute('muted')) {
this.click();
}
}
setVideoSrc(videoSrc) {
if (!this.videoEle) {
console.warn("MbioVideo");
return;
}
if (videoSrc) {
this.videoEle.src = videoSrc;
}
}
toggleSound() {
if (this.videoEle) {
this.videoEle.muted = !this.videoEle.muted;
}
}
onPageVisibilityChange() {
if (this.videoEle) {
if (document.hidden) {
this.videoEle.pause();
} else {
this.videoEle.play();
}
}
}
addIntersectionObserver() {
if (!this.videoEle) return;
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.play();
} else {
entry.target.pause();
}
});
}, { threshold: 0.6 });
observer.observe(this.videoEle);
}
}
customElements.define('mbio-video', MbioVideo);