Skip to content

Instantly share code, notes, and snippets.

@reggi
Created September 1, 2022 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reggi/fd433ffc73d623c1538937631b385cf9 to your computer and use it in GitHub Desktop.
Save reggi/fd433ffc73d623c1538937631b385cf9 to your computer and use it in GitHub Desktop.
Content Warning Web Component
<content-warning>
<img src="https://pbs.twimg.com/media/FblYTJZXwAAStJ6?format=jpg&name=small" alt="Veggie Sandwich" width=300>
</content-warning>
customElements.define('content-warning',
class extends HTMLElement {
constructor() {
super();
const template = document.createElement('template');
template.innerHTML = `
<style>
:host .center {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2;
text-align:center;
}
:host .wrapper {
position:relative;
width: fit-content;
}
:host .image-wrapper {
-webkit-filter:blur(20px);
filter: blur(20px);
cursor: pointer;
}
</style>
<div class="wrapper">
<div class="center">Content Warning (Click to show)</br><span class="alt"></span></div>
<div class="image-wrapper">
<!-- <img src="https://pbs.twimg.com/media/FblYTJZXwAAStJ6?format=jpg&name=small"> -->
<slot>
</div>
</div>
`
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(template.content.cloneNode(true));
const wrapper = shadowRoot.querySelector('.wrapper')
const imageWrapper = shadowRoot.querySelector('.image-wrapper')
const center = shadowRoot.querySelector('.center')
const img = this.children[0]
const alttext = img.getAttribute('alt') || ''
const alt = shadowRoot.querySelector('.alt')
if (alttext) alt.innerHTML = alttext
wrapper.addEventListener("click", () => {
imageWrapper.style.webkitFilter = "blur(0px)";
imageWrapper.style.filter = "blur(0px)";
center.style.display = 'none'
imageWrapper.style.cursor = 'auto'
});
imageWrapper.addEventListener("mouseleave", () => {
imageWrapper.style.webkitFilter = "blur(20px)";
imageWrapper.style.filter = "blur(20px)";
center.style.display = 'block'
imageWrapper.style.cursor = 'pointer'
});
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment