How To Detect A Click Outside An Element in Javascript?

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.

Exit mobile version