Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thibaut-decherit/a15b9b7d7495cc47184f772170614690 to your computer and use it in GitHub Desktop.
Save thibaut-decherit/a15b9b7d7495cc47184f772170614690 to your computer and use it in GitHub Desktop.
jQuery - Click outside of element listener

jQuery - Click outside of element listener

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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment