I am looking to create a custom lookup component using Lightning Web Components. I want to be able to detect when the user is clicking outside of the element so that I can close the dialog and/or clear the text if nothing is selected. I can't seem to use standard Javascript since template.contains(e.target)
and DOM traversal doesn't seem to detect whether the clicked element is inside of the component or not. Here is a sample of what I have attempted.
- DOM traversal
let parent = this.template.querySelector('.slds-form-element__row');//parent element
let targetElement = e.target; // clicked element
do {
if (targetElement == parent) {
window.console.log('clicked inside');
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while (targetElement);
window.console.log('clicked outside');
- template.contains(e.target)
if (this.template.querySelector('.slds-form-element__row').contains(e.target)) {
window.console.log('clicked inside');
} else {
window.console.log('clicked outside');
}
In both of these cases, clicked outside
is the only thing I will see since e.target
doesn't seem to exist within the DOM element, but I do know my click event (which I've attached to document
) is firing since I do see the console.log statement in my developer console.