Last active
October 13, 2020 14:57
-
-
Save yossan/0718e8e1690caaff29964d74fe35ad56 to your computer and use it in GitHub Desktop.
web components by using templates
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
<html> | |
<head></head> | |
<body> | |
<template id="my-paragraph"> | |
<style> | |
p { | |
color: white; | |
background-color: #666; | |
padding: 5px; | |
} | |
</style> | |
<p>My paragraph</p> | |
</template> | |
<script> | |
class MyParagraph extends HTMLElement { | |
constructor() { | |
super() | |
let template = document.getElementById('my-paragraph') | |
let templateContent = template.content | |
const shadowRoot = this.attachShadow({mode: 'open'}) | |
.appendChild(templateContent.cloneNode(true)) | |
} | |
} | |
customElements.define('my-paragraph', MyParagraph) | |
</script> | |
<my-paragraph></my-paragraph> | |
</body> | |
</html> |
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
<html> | |
<head></head> | |
<body> | |
<template id="my-paragraph"> | |
<style> | |
p { | |
color: white; | |
background-color: #666; | |
padding: 5px; | |
} | |
</style> | |
<p>My paragraph</p> | |
<p><slot name="my-text">My default text</slot></p> | |
</template> | |
<script> | |
class MyParagraph extends HTMLElement { | |
constructor() { | |
super() | |
let template = document.getElementById('my-paragraph') | |
let templateContent = template.content | |
const shadowRoot = this.attachShadow({mode: 'open'}) | |
.appendChild(templateContent.cloneNode(true)) | |
} | |
} | |
customElements.define('my-paragraph', MyParagraph) | |
</script> | |
<p>This is standard p element.</p> | |
<my-paragraph> | |
<span slot="my-text">Let's have some different text!</span> | |
</my-paragraph> | |
<my-paragraph> | |
<ul slot="my-text"> | |
<li>Let's have some different text!</li> | |
<li>In a list!</li> | |
</ul> | |
</my-paragraph> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment