Created
January 29, 2023 07:47
-
-
Save Rahmanism/f83dadcac1599f945c312324f2ca8e4b to your computer and use it in GitHub Desktop.
HTML Expandable UL - Custom element
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"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>HTML Custom Element - Expandable List</title> | |
</head> | |
<body> | |
<ul is="expandable-list"> | |
<li>First</li> | |
<li>Second</li> | |
<ul is="expandable-list" data-expanded="false"> | |
<li>First</li> | |
<li>Second</li> | |
</ul> | |
</ul> | |
<script> | |
class ExpandableList extends HTMLUListElement { | |
constructor() { | |
super() | |
this.style.position = 'relative' | |
this.toggleBtn = document.createElement('button') | |
this.toggleBtn.style.position = 'absolute' | |
this.toggleBtn.style.border = 'none' | |
this.toggleBtn.style.background = 'none' | |
this.toggleBtn.style.padding = 0 | |
this.toggleBtn.style.top = 0 | |
this.toggleBtn.style.left = '5px' | |
this.toggleBtn.style.cursor = 'pointer' | |
this.toggleBtn.innerText = '>' | |
this.toggleBtn.addEventListener('click', () => { | |
this.dataset.expanded = !this.isExpanded | |
}) | |
this.appendChild(this.toggleBtn) | |
} | |
get isExpanded() { | |
return ( | |
this.dataset.expanded !== 'false' && | |
this.dataset.expanded != null | |
) | |
} | |
static get observedAttributes() { | |
return ['data-expanded'] | |
} | |
attributeChangedCallback(name, oldValue, newValue) { | |
this.updateStyles() | |
} | |
connectedCallback() { | |
if (this.dataset.expanded == null) { | |
this.dataset.expanded = true | |
} | |
this.updateStyles() | |
} | |
updateStyles() { | |
const transform = this.isExpanded ? 'rotate(90deg)' : '' | |
this.toggleBtn.style.transform = transform | |
;[...this.children].forEach(child => { | |
child.style.display = this.isExpanded ? '' : 'none' | |
}) | |
this.toggleBtn.style.display = '' | |
} | |
} | |
customElements.define( | |
'expandable-list', | |
ExpandableList, | |
{ extends: 'ul' } | |
) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment