Created
March 8, 2024 15:38
-
-
Save arimet/78e4caf2d3364bca1fd6f6f0ef676758 to your computer and use it in GitHub Desktop.
Accordion created with LIT Web Component
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
import {LitElement, html, css} from 'lit'; | |
import {customElement, property} from 'lit/decorators.js'; | |
@customElement('accessible-accordion') | |
export class AccessibleAccordion extends LitElement { | |
static override styles = css` | |
.accordion { | |
border: 1px solid #ccc; | |
border-radius: 4px; | |
margin: 0 0 10px; | |
overflow: hidden; | |
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); | |
} | |
.accordion-header { | |
background-color: #f7f7f7; | |
color: #444; | |
cursor: pointer; | |
padding: 18px; | |
text-align: left; | |
border-bottom: 1px solid #ddd; | |
font-weight: bold; | |
display: flex; | |
justify-content: space-between; | |
} | |
.accordion-header[aria-expanded='true'] { | |
background-color: #ddd; | |
} | |
.accordion-content { | |
background-color: white; | |
border-top: 1px solid #ccc; | |
box-sizing: border-box; | |
transition: max-height 0.6s ease; | |
padding: 15px; | |
} | |
.accordion-content[aria-hidden='true'] { | |
max-height: 0; | |
overflow: hidden; | |
padding: 0px; | |
transition: max-height 0.6s ease; | |
} | |
`; | |
constructor() { | |
super(); | |
} | |
@property() expanded = false; | |
@property() titleAccordion = 'Default title'; | |
override render() { | |
return html` | |
<div class="accordion" tabindex="0" @keypress="${this.handleKeyDown}"> | |
<div | |
class="accordion-header" | |
role="button" | |
aria-expanded="${this.expanded}" | |
aria-controls="content-${this.id}" | |
@click="${this.toggle}" | |
> | |
<span>${this.titleAccordion}</span> | |
<span aria-hidden="true">${this.expanded ? '−' : '+'}</span> | |
</div> | |
<div | |
id="content-${this.id}" | |
class="accordion-content" | |
aria-hidden="${!this.expanded}" | |
> | |
<slot></slot> | |
</div> | |
</div> | |
`; | |
} | |
toggle() { | |
this.expanded = !this.expanded; | |
} | |
handleKeyDown(event: KeyboardEvent) { | |
if (event.key === 'Enter' || event.key === ' ') { | |
event.preventDefault(); | |
this.toggle(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment