0

I've built a set of dropdown menus in CSS and jQuery, but I'm struggling to allow closing any open menus by clicking outside/on the body. I've found existing similar questions that suggest using the .closest() method, but I can't seem to get this working:

$('body').click(function(e) {
    if ($(e.target).closest('.dropdown-menu').length === 0) {
        $('.dropdown-menu').hide();
    }
});

I've also tried the following:

$('body').on('click', function() {
  if ($('.dropdown-menu').is(':visible')) {
    $('.dropdown-menu').hide();
  }
});

Thanks!

Mario Parra
  • 1,504
  • 3
  • 21
  • 46
  • Have you considered using a purely CSS dropdown menu, or a prebuilt one? It may eliminate the need for this question. – Alexander Kerchum Jan 17 '17 at 19:59
  • Possible duplicate of [How do I detect a click outside an element?](http://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) – Alexander Kerchum Jan 17 '17 at 20:00
  • @AlexanderKerchum I tried in pure CSS, but I need the menus to expand on click, not hover. Haven't tried a pre-built solution since this is the last feature I need to implement. – Mario Parra Jan 17 '17 at 20:02
  • Perhaps using the `:focus` psuedo-element would be appropriate? Then you aren't sacrificing accessibility either. – Alexander Kerchum Jan 17 '17 at 20:06
  • How would I apply that? As I mentioned, I also tried various answers from the related question, which did not work. – Mario Parra Jan 17 '17 at 21:55

0 Answers0