Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created September 12, 2023 02:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cferdinandi/8edb86dfa22352d42f47f8a857315b82 to your computer and use it in GitHub Desktop.
Save cferdinandi/8edb86dfa22352d42f47f8a857315b82 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Components</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
</style>
</head>
<body>
<h1>Counter Button</h1>
<counter-button></counter-button>
<counter-button></counter-button>
<counter-button></counter-button>
<script>
customElements.define('counter-button', class extends HTMLElement {
/**
* The class constructor object
*/
constructor () {
// Always call super first in constructor
super();
// Track the count
this.count = 0;
// Render HTML
this.innerHTML =
`<button>Clicked ${this.count} Times</button>`;
}
/**
* Runs each time the element is appended to or moved in the DOM
*/
connectedCallback () {
let instance = this;
this.addEventListener('click', function () {
instance.count++;
instance.firstElementChild.textContent = `Clicked ${this.count} Times`;
});
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment