Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TEST Custom Web Elements
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>TEST Custom Elements</title>
<style>body{text-align: center;}</style>
</head>
<body>
<template id="clickBtn">
<style>
:host {
--green: yellowgreen;
--space: 10px;
}
.btn-container {
border: 1px solid rgba(0, 0, 0, .1);
width: 500px;
padding: var(--space);
text-align: center;
display: block;
margin: 20px auto;
}
.btn {
background-color: var(--green);
border: 0;
border-radius: 5px;
color: white;
padding: var(--space);
}
</style>
<div class="btn-container">
<div><slot name="intro"></slot><slot name="clickcount"></slot></div>
<button class="btn"><slot name="text"></slot></button>
</div>
</template>
<click-button intro="Total clicks: " text="Hacer click" clickcount="0"></click-button>
<click-button intro="Total clicks: " text="Hacer click" clickcount="0"></click-button>
<click-button intro="Total clicks: " text="Hacer click" clickcount="0"></click-button>
<click-button intro="Total clicks: " text="Hacer click" clickcount="0"></click-button>
<click-button intro="Total clicks: " text="Hacer click" clickcount="0"></click-button>
<script>
class ClickButton extends HTMLElement {
constructor(){
super()
this._text = null
this._intro = null
this._clickcount = 0
this.importDocument = document.currentScript.ownerDocument
}
connectedCallback(){
let shadowRoot = this.attachShadow({ mode: 'open' })
const t = document.querySelector('#clickBtn')
const instance = t.content.cloneNode(true)
instance.querySelector('[name="text"]').innerHTML = this.text
instance.querySelector('[name="intro"]').innerHTML = this.intro
instance.querySelector('[name="clickcount"]').innerHTML = this.clickcount
instance.querySelector('.btn').onclick = () => this.increment()
shadowRoot.appendChild(instance)
}
attributeChangedCallback(name, oldValue, newValue) {
if(this.shadowRoot){
this.shadowRoot.querySelector(`[name="${name}"]`).innerHTML = this[name]
}
}
increment(){
this.clickcount = this.clickcount + 1
}
static get observedAttributes(){
return [ 'intro', 'text', 'clickcount' ]
}
get clickcount(){
return this._clickcount
}
set clickcount(val){
this._clickcount = val
this.setAttribute('clickcount', this._clickcount)
}
get text(){
return this.getAttribute('text')
}
set text(val){
this._text = val
}
get intro(){
return this.getAttribute('intro')
}
set intro(val){
this._intro = val
}
}
window.customElements.define('click-button', ClickButton)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.