Skip to content

Instantly share code, notes, and snippets.

@nummi
Created October 8, 2019 04:16
Show Gist options
  • Save nummi/9a4b7ca10d2d34f6cb82fc88bb4a01df to your computer and use it in GitHub Desktop.
Save nummi/9a4b7ca10d2d34f6cb82fc88bb4a01df to your computer and use it in GitHub Desktop.
export default class DidLoadElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: "open" });
}
static get observedAttributes() {
return ["loaded"];
}
get isLoaded() {
return this.hasAttribute("loaded");
}
attributeChangedCallback(attr, oldValue, newValue) {
if (attr === "loaded") {
const button = this.shadowRoot.querySelector("button");
button.classList.add("loaded");
}
}
connectedCallback() {
const text = this.getAttribute("name") || "World";
this.shadowRoot.innerHTML = `
<style>
.btn {
position: relative;
top: 15px;
opacity: 0;
font-size: 200%;
transition: 0.4s all;
}
.loaded.btn {
top: 0;
opacity: 1;
}
</style>
<button class="btn">Hello ${text}!</button>
`;
const button = this.shadowRoot.querySelector("button");
this.observer = new IntersectionObserver(
entries => {
entries.forEach(e => {
if (!e.isIntersecting || this.isLoaded) {
return;
}
this.setAttribute("loaded", "yasss");
});
},
{
root: null,
rootMargin: "0px",
threshold: 0.5
}
);
this.observer.observe(button);
}
disconnectedCallback() {
this.observer.disconnect();
this.observer = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment