Javascript Detect click event outside of div [duplicate]
Asked Answered
H

10

21

I have a div with id="content-area", when a user clicks outside of this div, I would like to alert them to the fact that they clicked outside of it. How would I use JavaScript to solve this issue?

<div id = "outer-container">
   <div id = "content-area">
      Display Conents 
   </div>
</div>
Hovercraft answered 19/9, 2013 at 11:16 Comment(2)
1. What have you tried so far? can you post that code? 2. You want click detection anywhere outside the content-area (or) anywhere outside content-area but inside outer-container?Lx
@Harry, I don't care what steps the OP has taken. All I care to see is the solution to this problem. Making people post their own attempts in order to determine if they are worthy to answer is ridiculous. The purpose of this site is to be the main repository of answers relating to programming, making people posts their own attempts does not further this goal. On the other your other questions are well thought out and if they are the only reason you asked to see the attempts then that is fair. However I notice you have not provided an answer, so maybe you did not find the question worthy.Sedate
S
28

In pure Javascript

Check out this fiddle and see if that's what you're after!

document.getElementById('outer-container').onclick = function(e) {
    if(e.target != document.getElementById('content-area')) {
        document.getElementById('content-area').innerHTML = 'You clicked outside.';          
    } else {
        document.getElementById('content-area').innerHTML = 'Display Contents';   
    }
}

http://jsfiddle.net/DUhP6/2/

Stagnate answered 19/9, 2013 at 11:23 Comment(4)
This function is called when we click inside #content-area also.Lx
Bit faster: var element = document.getElementById('outer-container'); and then just if(e.target.id != element.id)Abstraction
You should use addEventListener( 'click', function(e) { ... }); all the time. not .onclick = funciton(e){ ... } function..Cenozoic
The fiddle link is expired.Propitious
P
16

The Node.contains() method returns a Boolean value indicating whether a node is a descendant of a given node or not

You can catch events using

document.addEventListener("click", clickOutside, false);
function clickOutside(e) {
   const inside = document.getElementById('content-area').contains(e.target);
}

Remember to remove the event listened in the right place

document.removeEventListener("click", clickOutside, false)
Purpleness answered 13/1, 2017 at 8:54 Comment(1)
This is easily the best answer. Needs more upvotes.Footbridge
P
12

Bind the onClick-Event to an element that is outside your content area, e.g. the body. Then, inside the event, check whether the target is the content area or a direct or indirect child of the content area. If not, then alert.

I made a function that checks whether it's a child or not. It returns true if the parent of a node is the searched parent. If not, then it checks whether it actually has a parent. If not, then it returns false. If it has a parent, but it's not the searched one, that it checks whether the parent's parent is the searched parent.

function isChildOf(child, parent) {
    if (child.parentNode === parent) {
      return true;
    } else if (child.parentNode === null) {
      return false;
    } else {
      return isChildOf(child.parentNode, parent);
    }
}

Also check out the Live Example (content-area = gray)!

Polad answered 19/9, 2013 at 11:45 Comment(1)
Well, DOM API has the equivalent of your recursive function : node.contains. And it has very good support (IE5+ !). Just discovered it today.Snuck
B
5

I made a simple and small js library to do this for you:

It hijacks the native addEventListener, to create a outclick event and also has a setter on the prototype for .onoutclick

Basic Usage

Using outclick you can register event listeners on DOM elements to detect whether another element that was that element or another element inside it was clicked. The most common use of this is in menus.

var menu = document.getElementById('menu')

menu.onoutclick = function () {
    hide(menu)
}

this can also be done using the addEventListener method

var menu = document.getElementById('menu')

menu.addEventListener('outclick', function (e) {
    hide(menu)
})

Alternatively, you can also use the html attribute outclick to trigger an event. This does not handle dynamic HTML, and we have no plans to add that, yet

<div outclick="someFunc()"></div>

Have fun!

Bowden answered 29/8, 2016 at 3:30 Comment(0)
M
2

Use document.activeElement to see which of your html elements is active.

Here is a reference: document.activeElement in MDN

Micamicaela answered 19/9, 2013 at 11:19 Comment(0)
S
1
$('#outer-container').on('click', function (e) {
     if (e.target === this) {
        alert('clicked outside');
     }
});

This is for the case that you click inside the outer-container but outside of the content-area.

Sweetscented answered 4/12, 2017 at 3:57 Comment(1)
This will not work if a child element is clicked in the container.Footbridge
G
0

use jquery as its best for DOM access

$(document).click(function(e){
 if($(e.target).is("#content-area") || $(e.target).closest("#content-area").length)
  alert("inside content area");
else alert("you clicked out side content area");
});
Gilbertson answered 19/9, 2013 at 11:21 Comment(1)
This is not a jquery question.Unsnarl
T
0

Here is the fiddle : http://jsfiddle.net/uQAMm/1/

$('#outercontainer:not(#contentarea)').on('click', function(event){df(event)} );
function df(evenement)
{
    var xstart = $('#contentarea').offset().left;
    var xend = $('#contentarea').offset().left + $('#contentarea').width();

    var ystart = $('#contentarea').offset().top;
    var yend = $('#contentarea').offset().top + $('#contentarea').height(); 

    var xx = evenement.clientX;
    var yy = evenement.clientY;

    if ( !(  ( xx >=  xstart && xx <=  xend ) && ( yy >=  ystart && yy <=  yend )) )
    {
        alert('out');
    }


}
Tailpipe answered 19/9, 2013 at 11:44 Comment(1)
This is not a jquery question.Prescott
U
0

Put this into your document:

<script>
document.onclick = function(e) {
  if(e.target.id != 'content-area') alert('you clicked outside of content area');
}
</script>
Uncalledfor answered 24/7, 2017 at 18:45 Comment(0)
A
0

Here is a simple eventListener that checks all parent elements if any contain the id of the element. Otherwise, the click was outside the element

html

<div id="element-id"></div>

js

const handleMouseDown = (ev) => {
    let clickOutside = true
    let el = ev.target
    while (el.parentElement) {
        if (el.id === "element-id") clickOutside = false
        el = el.parentElement
    }
    if (clickOutside) {
        // do whatever you wanna do if clicking outside
    }
}
document.addEventListener("mousedown", handleMouseDown)
Audraaudras answered 24/8, 2020 at 23:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.