js click outside code example

Example 1: javascript detect click outside element

var ignoreClickOnMeElement = document.getElementById('someElementID');

document.addEventListener('click', function(event) {
    var isClickInsideElement = ignoreClickOnMeElement.contains(event.target);
    if (!isClickInsideElement) {
        //Do something click is outside specified element
    }
});

Example 2: detect a click outside an element javascript

$(document).click((event) => {
  if (!$(event.target).closest('#element').length) {
    // the click occured outside '#element'
  }        
});

Example 3: on click outside div javascript

document.addEventListener("click", (evt) => {
    const flyoutElement = document.getElementById("flyout-example");
    let targetElement = evt.target; // clicked element

    do {
        if (targetElement == flyoutElement) {
            // This is a click inside. Do nothing, just return.
            document.getElementById("flyout-debug").textContent = "Clicked inside!";
            return;
        }
        // Go up the DOM
        targetElement = targetElement.parentNode;
    } while (targetElement);

    // This is a click outside.
    document.getElementById("flyout-debug").textContent = "Clicked outside!";
});

Example 4: how to click outside dom in javascript

// jQuery
$(window).click(function() {
//Hide the menus if visible
});

// JavaScript
const getBody = document.querySelector('body');
getBody.addEventListener('click', () => {
    //Hide the Menus if Visible
});

// Stop Propogation on Element you want to hide
$('#menucontainer').click(function(event){
    event.stopPropagation();
});

// Example
menu.addEventListener('click', (event) => {
    event.stopPropagation();
    // Open Menu
});