svelte use: ClickOutside directive
Posted at 2020-02-28

svelte use: ClickOutside directive


svelte use: ClickOutside directive


/** Dispatch event on click outside of node */
export function clickOutside(node) {
  
  const handleClick = event => {
    if (node && !node.contains(event.target) && !event.defaultPrevented) {
      node.dispatchEvent(
        new CustomEvent('click_outside', node)
      )
    }
  }

	document.addEventListener('click', handleClick, true);
  
  return {
    destroy() {
      document.removeEventListener('click', handleClick, true);
    }
	}
}


Comments 0

Post a Comment