How to close a dropdown if the user clicks another place on the page?

4

What is the best method to hide a div , which is fulfilling the role of dropdown , when the user clicks another place on the page?

At first, I value cross-browser solutions and without frameworks , but any extra application content using jQuery or even of CSS will be welcome.

    
asked by anonymous 23.12.2013 / 21:38

4 answers

7

A variation of the talles response, without jQuery, to IE9 + and other modern browsers:

document.addEventListener('mouseup', function(e) {
  var aEsconder = document.querySelector('[seu seletor]');
  var alvoDescendeDoAEsconder = (function(){
    var el = e.target.parentNode;
    while(el) {
      if(el === aEsconder) return true;
      el = el.parentNode;
    }
    return false;
  }());
  if (aEsconder !== e.target && !alvoDescendeDoAEsconder) 
    aEsconder.style.display = 'none';
});
    
23.12.2013 / 22:55
4
$(document).mouseup(function (e) {
  var aEsconder = $('[seu seletor]');
  if (!aEsconder.is(e.target) && aEsconder.has(e.target).length == 0) aEsconder.hide();
});

( source )

Test:

<!doctype html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><script>$(document).mouseup(function(e){varaEsconder=$("#conteudo1");
            if (!aEsconder.is(e.target) && aEsconder.has(e.target).length == 0) aEsconder.hide();
        });
    </script>
</head>    
<body>
    <div>
        <div id="conteudo1" style="min-height: 100px; background-color: yellow;">Se clicado aqui essa div continua sendo exibida</div>
        <div id="conteudo2" style="min-height: 100px; background-color: red;">Se clicado aqui, ou em outro lugar da página, a div acima sumirá</div>
    </div>
</body>    
</html>
    
23.12.2013 / 21:53
2

As your Drop-down will close if the user clicks anywhere on the page, you can use a generic selector to close it, just by adding this code:

    $('*').click(function(e){
         e.stopPropagation();
         if(!$(this).hasClass('.classeDoElementorAbrir')){
           $('#suaDiv').hide();
         } 
    });

and for it to open:

$('btAbrir').click(function(e){
     e.stopPropagation();
     $('#suaDiv').show();
});
    
23.12.2013 / 22:08
0

I made a basic modal example ( link ), which is quite simple to understand.

    
23.12.2013 / 22:04