Skip to content

Instantly share code, notes, and snippets.

@fransstudio2
Created April 30, 2020 15:30
Show Gist options
  • Save fransstudio2/20fdbff27a94d8471ba4284cc68de6ab to your computer and use it in GitHub Desktop.
Save fransstudio2/20fdbff27a94d8471ba4284cc68de6ab to your computer and use it in GitHub Desktop.
Click Outside
export function addClickOutside(el: HTMLElement, fun: Function) {
const elWithFun: HTMLElement & {
clickOutsideFun?: (this: Document, ev: MouseEvent) => any;
} = el;
elWithFun.clickOutsideFun = function (this: Document, event: MouseEvent) {
if (!el.contains(event.target as Node)) {
fun(event);
}
return true as any;
};
document.addEventListener("click", elWithFun.clickOutsideFun);
}
export function removeClickOoutside(el: HTMLElement) {
const elWithFun: HTMLElement & {
clickOutsideFun?: (this: Document, ev: MouseEvent) => any;
} = el;
if (elWithFun.clickOutsideFun) {
document.removeEventListener("click", elWithFun.clickOutsideFun);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment