frontend-taskdone/src/helpers/closeWhenClickedOutside.js
konrad 3313801174 Fix closing popups when clicking outside of them (#378)
Co-authored-by: kolaente <k@knt.li>
Reviewed-on: vikunja/frontend#378
Co-authored-by: konrad <konrad@kola-entertainments.de>
Co-committed-by: konrad <konrad@kola-entertainments.de>
2021-01-17 10:36:57 +00:00

27 lines
854 B
JavaScript

/**
* Calls the close callback when a click happened outside of the rootElement.
*
* @param event The "click" event object.
* @param rootElement
* @param closeCallback A closure function to call when the click event happened outside of the rootElement.
*/
export const closeWhenClickedOutside = (event, rootElement, closeCallback) => {
// We walk up the tree to see if any parent of the clicked element is the root element.
// If it is not, we call the close callback. We're doing all this hassle to only call the
// closing callback when a click happens outside of the rootElement.
let parent = event.target.parentElement
while (parent !== rootElement) {
if (parent === null || parent.parentElement === null) {
parent = null
break
}
parent = parent.parentElement
}
if (parent === rootElement) {
return
}
closeCallback()
}