Skip to content

Instantly share code, notes, and snippets.

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 wolframkriesing/5c424c8800f53456991729a192f7ac6d to your computer and use it in GitHub Desktop.
Save wolframkriesing/5c424c8800f53456991729a192f7ac6d to your computer and use it in GitHub Desktop.
The "web components from scratch" session at #jscc18, JSCraftCamp
<!DOCTYPE html>
<html>
<head>
<title>WebComponent from Scratch</title>
<script type="module" src="myH1.js"></script>
</head>
<body>
<style>
a {
color: orange;
}
</style>
<script>console.log('before my-h1');</script>
<h1 is="my-h1" hash="headline">WebComponent from Scratch</h1>
<script>console.log('after my-h1');</script>
</body>
const template = document.createElement('template');
template.innerHTML = `
<style>
a {
color: green;
}
</style>
<a href="">#</a>
<slot></slot>
`;
class MyH1 extends HTMLHeadingElement {
static get observedAttributes() {
return ['hash'];
}
constructor() {
console.log('in constructor');
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'hash') {
this.shadowRoot.querySelector('a')
.setAttribute('href', `#${this.getAttribute('hash')}`);
this.dispatchEvent(new Event('hashchange'));
}
}
}
customElements.define('my-h1', MyH1, {extends: 'h1'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment