-
-
Save jcicero518/5421254f243f2620ea110262735a6423 to your computer and use it in GitHub Desktop.
Web Components. https://gomakethings.com/sotb/
This file contains hidden or 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
<!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