Runs the callback whenever the user clicks outside of the specified element.
EventTarget.addEventListener()
to listen for 'click'
events.Node.contains()
to check if Event.target
is a descendant of element
and run callback
if not.const onClickOutside = (element, callback) => {
document.addEventListener('click', e => {
if (!element.contains(e.target)) callback();
});
};
onClickOutside('#my-element', () => console.log('Hello'));
// Will log 'Hello' whenever the user clicks outside of #my-element
JavaScript, Browser
Runs the callback whenever the user has stopped scrolling.
JavaScript, Browser
Runs the callback whenever the user input type changes (mouse
or touch
).
JavaScript, Browser
Creates a new MutationObserver
and runs the provided callback for each mutation on the specified element.