JSFiddle - React, Tailwind, and code Playground
HTML
<div id="foo">foobar</div>
<tx-c></tx-c>
JavaScript
const template = document.createElement('template')
template.innerHTML = `
<style>
.new { width:100%; }
</style>
<div id="new" class="new">
<p>txc custom element content</p>
</div>`
class txc extends HTMLElement {
constructor () {
super()
this.id = this.getAttribute('id')
this.sr = this.attachShadow({mode: 'open'})
this.sr.appendChild(template.content.cloneNode(true))
}
connectedCallback() {
console.log("connected")
const t = document.getElementById('foo')
this.resizeObserver = new ResizeObserver(this.onResize.bind(this))
this.resizeObserver.observe(this, { box : 'border-box' })
// this works with the following standard DOM element
// this.resizeObserver.observe(t, { box : 'border-box' })
this.addEventListener('click', this.onClick.bind(this))
}
onResize(entries) {
console.log("onResize")
window.requestAnimationFrame(() => {
if (!Array.isArray(entries) || !entries.length) return
for (let entry of entries) {
console.log('Width:', entry.contentRect.width );
console.log('Height:', entry.contentRect.height);
}
})
}
onClick(e) {
console.log("I'm clicked!")
}
}
window.customElements.define('tx-c', txc)