-
-
Save cferdinandi/dd453df00baaa84b153164ce5e4cc252 to your computer and use it in GitHub Desktop.
This file contains 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 Component</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
</head> | |
<body> | |
<my-library></my-library> | |
<script src="web-component.js"></script> | |
</body> | |
</html> |
This file contains 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
// JavaScript | |
customElements.define('my-library', class extends HTMLElement { | |
/** | |
* The class constructor object | |
*/ | |
constructor () { | |
// Gives element access to the parent class properties | |
super(); | |
// Inject some HTML | |
// (optional; HTML can already exist in the DOM) | |
this.innerHTML = | |
`<h1>Hi, universe!</h1> | |
<button>Activate Me</button>`; | |
// Define attributes | |
this.btn = this.querySelector('button'); | |
// Listen for events | |
this.btn.addEventListener('click', this); | |
// ALT: Shadow DOM | |
// Creates a shadow root | |
// this.root = this.attachShadow({mode: 'closed'}); | |
// Inject some HTML into the shadow DOM | |
// this.root.innerHTML = | |
// `<h1>Hi, universe!</h1> | |
// <button>Activate Me</button>`; | |
// Define attributes | |
// this.btn = this.root.querySelector('button'); | |
// Listen for events | |
// this.btn.addEventListener('click', this); | |
} | |
/** | |
* Handle events on the Web Component | |
* @param {Event} event The event object | |
*/ | |
handleEvent (event) { | |
console.log('clicked', event.target); | |
} | |
/** | |
* Runs each time the element is appended to or moved in the DOM | |
*/ | |
connectedCallback () { | |
console.log('connected!', this); | |
} | |
/** | |
* Runs when the element is removed from the DOM | |
*/ | |
disconnectedCallback () { | |
console.log('disconnected', this); | |
} | |
// An array of attributes to observe | |
static observedAttributes = ['greeting']; | |
/** | |
* Runs when the value of an attribute is changed on the component | |
* @requires observedAttributes() method | |
* @param {String} name The attribute name | |
* @param {String} oldValue The old attribute value | |
* @param {String} newValue The new attribute value | |
*/ | |
attributeChangedCallback (name, oldValue, newValue) { | |
console.log('changed', name, oldValue, newValue, this); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment