How To Detect A Click Outside An Element in Javascript?

Table of Contents

When developing apps, especially single-page applications, it is important to detect if clicks were triggered outside of an element. This is the function I use to do that.

function outsideClick(event, notelem)	{
    notelem = $(notelem); // jquerize (optional)
    // check outside click for multiple elements
    var clickedOut = true, i, len = notelem.length;
    for (i = 0;i < len;i++)  {
        if (event.target == notelem[i] || notelem[i].contains(event.target)) {
            clickedOut = false;
        }
    }
    if (clickedOut) return true;
    else return false;
}

This is the Browser Click Event, from which the click  event is triggered

notelem (notelem) refers to the element or multiple elements that you will see if you click on it. The function will return false if the user clicks on one of these elements. The function will return true if the user clicks on elements other than those mentioned.

Usage

var modal = document.getElementById("modal");
window.addEventListener('click', function(e) {
   if (outsideClick(e, modal)) {
   		// close modal
   }
});

All major browsers (IE 9+ and above) support this function.

How To Use Data Analytics To Improve Email Marketing Campaigns Top 8 Dominating Mobile App Trends in 2022 How to make a car safe for long journeys? Everything You Expect to Learn About VPN for Windows Top 7 Benefits of B2B Marketing Strategy Characteristics Held in common with All Customer-Friendly LMS Solutions