<template id="counter">
  <style>
    button {
      background-color: red;
      color: white;
      padding: 4px;
    }
  </style>
  <button>Click me</button>
  <span id="times">0</span>
</template>
<my-counter></my-counter>
class MyCounter extends HTMLElement {
  times = 0;
  constructor() {
    super();
      const template = document.getElementById('counter');
      const shadowRoot = this.attachShadow({mode: 'open'});
      shadowRoot.appendChild(template.content.cloneNode(true));
      this.onClick = this.onClick.bind(this);
      this.shadowRoot.querySelector('button').addEventListener('click', this.onClick);
  }
  onClick() {
    this.times += 1;
    this.shadowRoot.querySelector('#times').textContent = this.times;
  }
}
customElements.define("my-counter", MyCounter);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.