Skip to content

Instantly share code, notes, and snippets.

@yinonov
Last active November 27, 2020 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yinonov/6f174e08e23ea943df44633bbf4d3c61 to your computer and use it in GitHub Desktop.
Save yinonov/6f174e08e23ea943df44633bbf4d3c61 to your computer and use it in GitHub Desktop.
Vivid "short" - Autocomplete
<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>
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