Created
August 10, 2018 15:45
-
-
Save wolframkriesing/5c424c8800f53456991729a192f7ac6d to your computer and use it in GitHub Desktop.
The "web components from scratch" session at #jscc18, JSCraftCamp
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
<!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> |
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
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