Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/content/components/dropdown.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ webcomponent = true

Wrap in `<ot-dropdown>`. Use `popovertarget` on the trigger and `popover` on the target. If a dropdown `<menu>`, items use `role="menuitem"`.

#### Attributes

- `close-on-click` — close the popover when a `role="menuitem"` is clicked. By default, the popover stays open on item click and only closes on outside click or another toggle.

{% demo() %}
```html
<ot-dropdown>
Expand All @@ -27,6 +31,28 @@ Wrap in `<ot-dropdown>`. Use `popovertarget` on the trigger and `popover` on the
```
{% end %}

### Close on click

Add the `close-on-click` attribute to dismiss the popover as soon as a menu item is activated.

{% demo() %}
```html
<ot-dropdown close-on-click>
<button popovertarget="demo-menu-coc" class="outline">
Options
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m6 9 6 6 6-6" /></svg>
</button>
<menu popover id="demo-menu-coc">
<button role="menuitem">Profile</button>
<button role="menuitem">Settings</button>
<button role="menuitem">Help</button>
<hr>
<button role="menuitem">Logout</button>
</menu>
</ot-dropdown>
```
{% end %}

### Popover

`<ot-dropdown>` can also be used to show popover dropdown elements.
Expand Down
8 changes: 8 additions & 0 deletions src/js/dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class OtDropdown extends OtBase {

this.#menu.addEventListener('toggle', this);
this.#menu.addEventListener('keydown', this);
this.#menu.addEventListener('click', this);

this.#position = () => {
// Position has to be calculated and applied manually because
Expand Down Expand Up @@ -65,6 +66,13 @@ class OtDropdown extends OtBase {
if (next >= 0) this.#items[next].focus();
}

onclick(e) {
if (!this.hasAttribute('close-on-click')) return;
if (!e.target.closest('[role="menuitem"]')) return;

this.#menu.hidePopover();
}

cleanup() {
window.removeEventListener('scroll', this.#position, true);
window.removeEventListener('resize', this.#position);
Expand Down