Last active
November 27, 2020 07:03
-
-
Save yinonov/6f174e08e23ea943df44633bbf4d3c61 to your computer and use it in GitHub Desktop.
Vivid "short" - Autocomplete
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
<div style="position: relative;"> | |
<vwc-textfield | |
id="textfield" | |
outlined | |
list="menu" | |
label="Choose browser" | |
></vwc-textfield> | |
<vwc-menu id="menu"> | |
<vwc-list-item>Edge</vwc-list-item> | |
<vwc-list-item>Firefox</vwc-list-item> | |
<vwc-list-item>Chrome</vwc-list-item> | |
<vwc-list-item>Opera</vwc-list-item> | |
<vwc-list-item>Safari</vwc-list-item> | |
</vwc-menu> | |
</div> |
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
const textfield = document.getElementById("textfield"); | |
const menu = document.getElementById("menu"); | |
configureMenuSettings(menu, textfield); | |
textfield.addEventListener("focus", openMenu); | |
menu.addEventListener("mousedown", e => e.preventDefault()); | |
menu.addEventListener("selected", onSelect); | |
textfield.addEventListener("mousedown", onTextfieldMousedown); | |
document.body.addEventListener("click", onTextfieldBodyClick, { | |
capture: true | |
}); | |
function onInput() { | |
const { value } = textfield; | |
menu?.items.forEach(item => { | |
item.style.display = "none"; | |
}); | |
} | |
function onTextfieldBodyClick(e) { | |
if (e.target === textfield) { | |
e.stopImmediatePropagation(); | |
} | |
} | |
function onTextfieldMousedown(e) { | |
if (textfield === document.activeElement) { | |
openMenu(); | |
} | |
} | |
function openMenu() { | |
!menu.open && menu?.items.length && menu.show(); | |
} | |
function onSelect({ target, detail: { index } }) { | |
const { textContent } = target?.items[index]; | |
textfield.value = textContent; | |
} | |
function configureMenuSettings(menu, anchor) { | |
menu.anchor = anchor; | |
menu.defaultFocus = "NONE"; | |
menu.corner = "BOTTOM_START"; | |
menu.multi = false; | |
menu.quick = true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment