Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Created June 14, 2019 13:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosePedroDias/a8182390bddee79c78205e3ca7d9262d to your computer and use it in GitHub Desktop.
Save JosePedroDias/a8182390bddee79c78205e3ca7d9262d to your computer and use it in GitHub Desktop.
custom element
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>webcomponents test</title>
<link
href="data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQEAYAAABPYyMiAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAAF0lEQVRIx2NgGAWjYBSMglEwCkbBSAcACBAAAeaR9cIAAAAASUVORK5CYII="
rel="icon"
type="image/x-icon"
/>
<style>
ui-tab-toggle {
border: 1px solid #222;
}
ui-tab-toggle a {
text-decoration: none;
display: inline-block;
padding: 2px 4px;
}
ui-tab-toggle .selected {
color: red;
font-weight: bold;
}
ui-tab-content {
display: block;
border: 1px solid gray;
}
</style>
</head>
<body>
<script>
class UiTabToggle extends HTMLElement {
update(idx) {
const els = Array.prototype.slice.apply(this.children);
els.forEach((el, i) => {
el.className = idx === i ? 'selected' : '';
});
const contentEl = this.parentNode.querySelector('ui-tab-content');
contentEl && contentEl.setAttribute('chosen', idx);
}
connectedCallback() {
const items = this.getAttribute('data').split(',');
items.forEach((it, idx) => {
const aEl = document.createElement('a');
aEl.setAttribute('href', '#' + idx);
aEl.appendChild(document.createTextNode(it));
this.appendChild(aEl);
});
this.addEventListener('click', (ev) => {
ev.preventDefault();
ev.stopPropagation();
const el = ev.target;
const idx = parseInt(el.getAttribute('href').substring(1), 10);
this.update(idx);
});
this.update(0);
}
}
customElements.define('ui-tab-toggle', UiTabToggle);
class UiTabContent extends HTMLElement {
static get observedAttributes() {
return ['chosen'];
}
get chosen() {
return parseInt(this.getAttribute('chosen'), 10);
}
set chosen(idx) {
this.setAttribute('chosen', idx);
}
update() {
let idx = this.chosen;
//console.log('update', idx);
if (isNaN(idx)) {
idx = 0;
}
const els = Array.prototype.slice.apply(this.children);
els.forEach((el, i) => {
el.style.display = idx === i ? '' : 'none';
});
}
connectedCallback() {
this.update();
}
attributeChangedCallback(attr, v0, v1) {
if (attr === 'chosen' && this.isConnected) {
this.update();
}
}
}
customElements.define('ui-tab-content', UiTabContent);
</script>
<ui-tab-toggle data="A,B"></ui-tab-toggle>
<ui-tab-content>
<div>ONE</div>
<div>TWO</div>
</ui-tab>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment