GBeck
GBeck

Reputation: 402

How to close dropdown menu when clicking outside the menu container?

I would like to know how I can close the dropdown menu (and a popup window) when clicking outside the menu/popup.

I haven't found anything successful yet...

Thanks in advance for your help!

(Using a Mac, Chrome and Bootstrap4)

<div class="ed-opts">
  <button type="button" class="btn btn-link ed-opts-open">Change</button>
  <ul class="ed-options">
    <li><a href="#" title="">Option 1</a></li>
    <li><a href="#" title="">Option 2</a></li>
    <li><a href="#" title="">Option 3</a></li>
    <li><a href="#" title="">Option 4</a></li>
    <li><a href="#" title="">Option 5</a></li>
  </ul>
</div>

Upvotes: 1

Views: 88

Answers (1)

AntG
AntG

Reputation: 1294

You might need to adjust how you select the right elements with jQuery, but in essence something like this should work:

function toggleMenu(){
    if($('.btn-link').hasClass('ed-opts-open')){
       $('.btn-link').removeClass('ed-opts-open'); 
    }else{
       $('.btn-link').addClass('ed-opts-open'); 
       $('.ed-opts').focus();
    }
}

$('.btn-link').on('click',toggleMenu)
$('.ed-opts').on('blur',toggleMenu)

Upvotes: 1

Related Questions