Created
July 10, 2020 05:18
-
-
Save mikelpr/d2fe4bf4b37a2cb951b6e53753c860d8 to your computer and use it in GitHub Desktop.
responsive YouTube embed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class YTEmbed extends HTMLElement { | |
static get observedAttributes() { return ['videoid', 'ratio']; } | |
constructor() { | |
super(); | |
this.shadow = this.attachShadow({mode: "open"}); | |
this.redraw(); | |
} | |
attributeChangedCallback(name, oldValue, newValue) { | |
if (name == "ratio") this.setRatioStyle(); | |
else this.redraw(); | |
} | |
redraw() { | |
this.shadow.childNodes.forEach(ele => {this.shadow.removeChild(ele)}); | |
this.setRatioStyle(); | |
const embedRef = `https://www.youtube.com/embed/${this.getAttribute("videoid")}`; | |
const ytframe = document.createElement("iframe"); | |
((_) => { | |
_.src = embedRef; | |
_.frameBorder = "0"; | |
_.allowFullscreen = true; | |
_.allow = "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"; | |
}) (ytframe); | |
((_) => { | |
_.position = "absolute"; | |
_.top = _.right = _.bottom = _.left = 0; | |
_.width = _.height = "100%"; | |
}) (ytframe.style); | |
this.shadow.appendChild(ytframe); | |
} | |
setRatioStyle() { | |
let ratio = this.getAttribute("ratio"); | |
if (ratio == null) ratio = 16/9; | |
else if (ratio.includes(":")) { | |
const ratarr = ratio.split(":"); | |
ratio = ratarr[0]/ratarr[1]; | |
} | |
else ratio = parseFloat(ratio); | |
((_) => { | |
_.paddingTop = `${(1/ratio)*100}%`; | |
_.display = "block"; | |
_.position = "relative"; | |
_.background = "black"; | |
_.width = "100%"; | |
}) (this.style); | |
} | |
} | |
window.customElements.define('yt-embed', YTEmbed); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment