Can be used to close an element previously opened by the user (e.g. a menu, a collapse...)
example.js:
$('#my-element').click(function () {
if (!$(this).hasClass('open')) {
openElement();
} else {
closeElement();
}
});
function openElement() {
// [...] Your logic to open the element.
$(this).addClass('open');
document.body.addEventListener('click', clickOutsideElementListener);
}
function closeElement() {
// [...] Your logic to close the element.
$(this).removeClass('open');
// The element has been closed so we can remove the click event listener.
document.body.removeEventListener('click', clickOutsideElementListener);
}
function clickOutsideElementListener(event) {
/*
Add your own tests to check if click is inside the element and should therefore
not trigger the closing code.
*/
if (event.target.id === 'my-element') {
return;
}
closeElement();
}