A Pen by Thomas Reggi on CodePen.
Created
September 1, 2022 21:11
-
-
Save reggi/fd433ffc73d623c1538937631b385cf9 to your computer and use it in GitHub Desktop.
Content Warning Web Component
This file contains 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
<content-warning> | |
<img src="https://pbs.twimg.com/media/FblYTJZXwAAStJ6?format=jpg&name=small" alt="Veggie Sandwich" width=300> | |
</content-warning> |
This file contains 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
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