Skip to content

Instantly share code, notes, and snippets.

@subzey
Last active October 30, 2019 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subzey/ca950f8ef753214bd6d39ba925a0945f to your computer and use it in GitHub Desktop.
Save subzey/ca950f8ef753214bd6d39ba925a0945f to your computer and use it in GitHub Desktop.
Outside setTimeout
<!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