Register clickout event in javascript
npm install clickout --save
import ClickOut from 'clickout';
export default class ClickOut {
// Emit a 'clickout' event each time you click outside of a specific HTMLElement
static bindCustomEvent(element: string | HTMLElement): destroyClickOut;
// Trigger a function only when you click outside of a specific HTMLElement
static bind(element: string | HTMLElement, onClickOut: onCLickOut): destroyClickOut;
// Destroy all listeners for emit/trigger clickout event/function
static destroy(element: string | HTMLElement): void;
}
CustomEvent is supported in all major browsers. If you need support for old browsers check this polyfill.
const element = document.querySelector('#myElement');
// Emit 'clickout' event when you click outside of element
ClickOut.bindCustomEvent(element);
// Listen on 'clickout' event emitted from the element
element.addEventListener('clickout', (e) => {
console.log(`You clicked an element outside of ${e.target}`);
})
// elsewhere on your code
element.addEventListener('clickout', (e) => {
console.log(`I'm triggered too on clickout ${e.target}!`)
})
const element = document.querySelector('#myElement');
// Trigger a function only when you click outside of a specific HTMLElement
ClickOut.bind(element, (e) => {
console.log(`You clicked ${e.target} and it's out of ${element}`)
});
const element = document.querySelector('#myElement');
ClickOut.bindCustomEvent(element);
element.addEventListener('clickout', (e) => {
console.log(`You clicked an element outside of ${e.target}`);
});
ClickOut.destroy(element);
/**
* ------------------------------
* Is the same as:
*/
const destroyClickOutElement = ClickOut.bindCustomEvent(element);
element.addEventListener('clickout', (e) => {
console.log(`You clicked an element outside of ${e.target}`);
});
destroyClickOutElement();
const element = document.querySelector('#myElement');
ClickOut.bind(element, (e) => {
console.log(`You clicked ${e.target} and it's out of ${element}`)
});
ClickOut.destroy(element);
/**
* ------------------------------
* Is the same as:
*/
const destroyClickOutElement = ClickOut.bind(element, (e) => {
console.log(`You clicked ${e.target} and it's out of ${element}`)
});
destroyClickOutElement();