Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event on a click everywhere on the page outside of the specific div

I'd like to hide a div when user click anywhere on the page outside of that div. How can I do that using raw javascript or jQuery?

like image 413
sumek Avatar asked Nov 26 '08 16:11

sumek


People also ask

How do you check if a click is outside a div?

addEventListener('click', function(e){ if (document. getElementById('clickbox'). contains(e. target)){ // Clicked in box } else{ // Clicked outside the box } });

How do I detect a click outside an 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.

Can you add a click event to a div?

To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div. to add a div with a class.

How do I hide a div when the user clicks outside?

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.


2 Answers

Attach a click event to the document to hide the div:

$(document).click(function(e) {
   $('#somediv').hide();
});

Attach a click event to the div to stop clicks on it from propagating to the document:

$('#somediv').click(function(e) {
   e.stopPropagation();
});
like image 200
Eran Galperin Avatar answered Oct 09 '22 08:10

Eran Galperin


First idea, in raw javascript (from this post):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <style type="text/css">
      <!--
      #mydiv{
        background-color: #999999;
        height: 100px;
        width: 100px;
      }
      -->
    </style>
    <script type="text/javascript">
      document.onclick=check;
      function check(e)
      {
        var target = (e && e.target) || (event && event.srcElement);
        var obj = document.getElementById('mydiv');
        if(target!=obj){obj.style.display='none'}
      }
    </script>
  </head>
  <body>
    <div id="mydiv">my div</div>
  </body>
</html> 

Tested with IE6 and FireFox3.1, it does work as advertised.

like image 43
VonC Avatar answered Oct 09 '22 08:10

VonC