Skip to content

Instantly share code, notes, and snippets.

@kristoferjoseph
Last active November 28, 2023 19:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristoferjoseph/dd5d22018a0f7feedd4ee18f25a040a8 to your computer and use it in GitHub Desktop.
Save kristoferjoseph/dd5d22018a0f7feedd4ee18f25a040a8 to your computer and use it in GitHub Desktop.
Single file MyMessage Custom Element pure function that enables adding tags dynamically in the browser with JavaScript
export default function MyMessage({ html, state }) {
const { attrs } = state
const { message='' } = attrs
return html`
<h1>${ message }</h1>
<script type="module">
class MyMessage extends HTMLElement {
constructor() {
super()
const templateID = `${this.tagName.toLowerCase()}-template`
const template = document.getElementById(templateID)
if (template) {
this.template = template
}
else {
this.template = document.createElement('template')
this.template.innerHTML = `<h1></h1>`
this.template.setAttribute('id', templateID)
}
// Do not replace children if already present from SSR
if (!this.hasAttribute('enhanced')) {
this.replaceChildren(this.template.content.cloneNode(true))
}
this.heading = this.querySelector('h1')
}
static get observedAttributes() {
return [ 'message' ]
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
if (name === 'message') {
this.heading.textContent = newValue
}
}
}
}
customElements.define('my-message', MyMessage)
</script>
`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment