Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progress. Inside the async firstUpdated()
function, I have set up an event listener as per the guidelines mentioned in their documentation at this link. While logging out dropdown
works fine, the issue arises when I try to log out target
, as it returns the entire root element
<custom-drop-down>...</custom-drop-down>
each time, which although somewhat correct, lacks specificity. Any suggestions or alternative approaches to handle outside click events are welcome.
As a reference, I am attempting to replicate something similar to what has been already created (though the source code is not visible) at this link:
async firstUpdated() {
await new Promise((r) => setTimeout(r, 0));
this.addEventListener('click', event => {
const dropdown = <HTMLElement>this.shadowRoot?.getElementById('dropdown-select');
const target = <HTMLElement>event.target;
if (!dropdown?.contains(target)) {
console.log('im outside');
}
});
}
@customElement('custom-drop-down')
public render(): TemplateResult {
return html`
<div>
<div id="dropdown-select" @action=${this.updateValue}>
<div class="current-selection" @click=${this.toggleDropdown}>
${this.value}
</div>
<div class="dropdown-options" id="dropdown-options">
${this.dropdownItems(this.options)}
</div>
</div>
</div>
`;
}