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
Liked the article? Follow me on Twitter, or help Hyvor grow by funding Hyvor Talk.
Latest on Hyvor Developer
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Image for All About MYSQLI Prepared Statements in PHP
All About MYSQLI Prepared Statements in PHP
Image for Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image for PHP Contact Form - The Email Method
PHP Contact Form - The Email Method
Image for The Best Way to Perform MYSQLI Prepared Statements in PHP
The Best Way to Perform MYSQLI Prepared Statements in PHP
Related Articles
2