Below you can find a stupid simple web component, thatβs it.
β
On this page I defined the following template:
<template>
<style>
#cig-component-container button {
font-size: 1.5rem;
}
#cig-component-container h1 {
background: black;
color: white;
font-weight: bold;
font-size: 2rem;
padding: 0.75rem 1.5rem;
}
</style>
<div id="cig-component-container">
<button>next</button>
<br>
<h1></h1>
</div>
</template>
This gets then used by the cig.mjs
file, which defines the webcomponent itself:
class CigComponent extends HTMLElement {
constructor() {
super()
}
connectedCallback() {
this.render()
this.attachEvents()
}
disconnectedCallback() {
this.removeEventListener('click', this.handleButtonClick)
}
render() {
const template = document.querySelector('template')
const clone = template.content.cloneNode(true)
const title = clone.querySelector('#cig-component-container h1')
title.innerText = randomSentence()
this.appendChild(clone)
}
attachEvents() {
const button = this.querySelector('#cig-component-container button')
button.addEventListener('click', this.handleButtonClick.bind(this))
}
handleButtonClick () {
const title = this.querySelector('#cig-component-container h1')
title.innerText = randomSentence()
}
}
function randomSentence() {
const sentences = [
"Programming can harm you and others around you",
"Programming harms you, and smoking harms others.",
"Prioritize well-being, avoid excessive coding and smoking.",
"Coding and smoking carry risks for you and those nearby.",
"Healthy habits: code wisely, quit smoking.",
"Protect yourself and the environment by avoiding smoking while coding.",
]
return sentences[Math.floor(Math.random() * sentences.length)]
}
customElements.define('cig-component', CigComponent)
Here I am using the <cig-component>
, you can play with it here π