Skip to content

Instantly share code, notes, and snippets.

@itproto
Forked from dalamgir/shadow-dom-final.js
Created April 9, 2017 00:12
Show Gist options
  • Save itproto/c7466add7d15d0f3610e850ad4e2993e to your computer and use it in GitHub Desktop.
Save itproto/c7466add7d15d0f3610e850ad4e2993e to your computer and use it in GitHub Desktop.
class NameTag extends HTMLElement {
// Assign a private variable to store the name property
constructor() {
super();
this._name = '';
this._rendered = false;
}
// Static method that returns an array with the name of
// all the properties that should be observed
static get observedAttributes() { return ["name"]; }
// A lifecycle call back that gets invoked every time
// a property in the observation list changes. This method
// leaves room to do some dirty checking
attributeChangedCallback(name, oldValue, newValue) {
if (newValue !== oldValue && name === 'name') {
this.name = newValue;
}
}
render() {
this._shadowRoot = this.attachShadow({mode: 'open'});
this._shadowRoot.innerHTML = `
<style>
.card {
height: 100px;
width: 200px;
background: #ed1c40;
text-align: center;
padding-top: 10px;
border-radius: 10px;
color: white;
font-family: "Comic Sans MS"
}
.name-container {
height: 60px;
width: 170px;
line-height: 60px;
background: white;
margin: 0 auto;
margin-top: 10px;
border-radius: 10px;
color: black;
}
</style>
<div class="card">
Hi! My name is
<div class="name-container">
</div>
</div>
`;
this._rendered = true;
}
// ES6 setter method for the name property which gets
// called when the value for `name` is assigned
set name(val) {
this._name = val;
if (!this._rendered) this.render();
this._shadowRoot.querySelector('.name-container').innerHTML = this.name;
}
// ES6 getter method for the name property which gets
// called when the value for `name` is read
get name() {
return this._name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment