Last active
October 30, 2019 16:47
-
-
Save subzey/ca950f8ef753214bd6d39ba925a0945f to your computer and use it in GitHub Desktop.
Outside setTimeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
</head> | |
<body> | |
<button>Click me</button> | |
<script> | |
function addOutsideEventListener(outsideContainer, handler, ownerDocument, events) { | |
function handleOutsideEvent(e) { | |
var target = e.target; | |
if (handler !== undefined && outsideContainer !== null && target !== null && target.ownerDocument === ownerDocument) { | |
if (!outsideContainer.contains(target)) { | |
handler(e); | |
} | |
} | |
} | |
// Wait until the "this" event settles | |
var timeoutId = setTimeout(function () { | |
if (events.click) { | |
ownerDocument.addEventListener('click', handleOutsideEvent, false); | |
} | |
if (events.mouseDown) { | |
ownerDocument.addEventListener('mousedown', handleOutsideEvent, false); | |
} | |
if (events.touchEnd) { | |
ownerDocument.addEventListener('touchend', handleOutsideEvent, false); | |
} | |
if (events.touchStart) { | |
ownerDocument.addEventListener('touchstart', handleOutsideEvent, false); | |
} | |
}, 0); | |
return function () { | |
// Doesn't matter if it was already fired or no | |
clearTimeout(timeoutId); | |
ownerDocument.removeEventListener('click', handleOutsideEvent, false); | |
ownerDocument.removeEventListener('mousedown', handleOutsideEvent, false); | |
ownerDocument.removeEventListener('touchend', handleOutsideEvent, false); | |
ownerDocument.removeEventListener('touchstart', handleOutsideEvent, false); | |
}; | |
} | |
</script> | |
<script> | |
document.querySelector('button').addEventListener('click', function(e){ | |
var el = document.createElement('h1'); | |
el.innerText = 'Hello'; | |
el.style.border = 'solid red 1px'; | |
document.body.appendChild(el); | |
console.log('setting up'); | |
var teardown = addOutsideEventListener( | |
el, | |
function(e){ | |
console.log(e.type, 'outside'); | |
teardown(); | |
el.parentNode.removeChild(el); | |
}, | |
el.ownerDocument, | |
{click: true} | |
) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment