Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Last active October 25, 2023 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cferdinandi/dd453df00baaa84b153164ce5e4cc252 to your computer and use it in GitHub Desktop.
Save cferdinandi/dd453df00baaa84b153164ce5e4cc252 to your computer and use it in GitHub Desktop.
<!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>
// JavaScript
customElements.define('my-library', class extends HTMLElement {
/**
* The class constructor object
*/
constructor () {
// Always call super first in constructor
super();
// Inject some HTML
this.innerHTML =
`<h1>Hi, universe!</h1>`;
// 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>`;
}
/**
* 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);
}
/**
* 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);
}
/**
* Create a list of attributes to observe
* @return {Array} The attributes to observe
*/
static get observedAttributes () {
return ['greeting'];
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment