Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Detect click event outside of div

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>
like image 478
Dibish Avatar asked Sep 19 '13 11:09

Dibish


People also ask

How do I know if I clicked outside a div?

To detect click outside div using JavaScript, we can check if e. target doesn't equal the inner element. document. getElementById("outer-container").

How do you trigger an event when clicking outside the element?

Trigger Event When Clicking Outside an Element with jQuery to add a div and we want to detect whether we clicked outside of it. Then we write: $('html'). click((e) => { if (e.target.id !==

How do you hide a div when the user clicks outside of it using JavaScript?

To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.

How do I check my outside click element?

To detect click outside element with JavaScript, we can use the element's contains method. const specifiedElement = document. getElementById("a"); document. addEventListener("click", (event) => { const isClickInside = specifiedElement.


Video Answer


2 Answers

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/

like image 85
jollelj Avatar answered Sep 29 '22 12:09

jollelj


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)
like image 41
Jan Vorcak Avatar answered Sep 29 '22 13:09

Jan Vorcak