How To Detect A Click Outside An Element in Javascript?

Detecting if a click was triggered outside an element is quite needed when you develop apps, specially single page applications. Here's the function that I use for 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;
}

Here event is the Browser Click Event from where the click event is triggered

notelem (Not Elem) is the element (or multiple elements) that you check if clicked. If the user clicks on any of these elements, the function will return false. If the user clicks outside of these elements, the function will return true.

Usage


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

This function is supported by all the major browsers (IE 9+)

Tagged: Javascript
You can connect with me on Twitter or Linkedin.
Latest on My Blog
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Laravel High CPU Usage Because of File-based Session Storage
Laravel High CPU Usage Because of File-based Session Storage
Image for Resizing Droplets: A Personal Experience
Resizing Droplets: A Personal Experience
Image for Moving our CDN (10+ GB images) to a new server
Moving our CDN (10+ GB images) to a new server
Image for Disqus, the dark commenting system
Disqus, the dark commenting system
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Related Articles
1245