1

Here is a javascript dropdown menu. I got it from some site it works fine but problem is the dropdown menu closes only when menu button is clicked. How can I make dropdown menu close even when I click any where else on page.

<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">ddm</button>
<div id="myDropdown" class="dropdown-content">
    <a href=""></a>
    <a href=""></a>
    <a href=""></a>
</div>
</div>

<script type="text/javascript">
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown");
var i;
for (i = 0; i < dropdowns.length; i++) {
  var openDropdown = dropdowns[i];
  if (openDropdown.classList.contains('show')) {
    openDropdown.classList.remove('show');
   }
  }
 }
}
</script>
bɪˈɡɪnə
  • 1,087
  • 2
  • 23
  • 46

3 Answers3

1

Try the code below, it should work

$(document).click(function(event) { 
    if(!$(event.target).closest('#myDropdown').length) {
        if($('#myDropdown').is(":visible")) {
            $('#myDropdown').hide()
        }
    }        
})
Arif
  • 1,617
  • 9
  • 18
  • Confirmed this works for me in Edge. I've also messaged W3Schools to point out the issue in their dropdown example, which is where you might have got the code. – Savage May 19 '17 at 07:44
0

You can use this code:-

var dropdown = $('dropdown_selector');
$(document).click(function(e){
if(e.target === dropdown.get(0))
    {
        // hide dropdawn code here
    }
});
sajalsuraj
  • 922
  • 15
  • 29
0

onBlur event is triggered when an element loses focus.

document.getElementById("myDropdown").onblur = function() {
    myFunction();
}
P. Jairaj
  • 1,033
  • 1
  • 6
  • 8
  • but it does not have focus... – epascarello Jan 25 '16 at 13:56
  • This might apply when you have a drop-down triggered by a hover, but in other cases you open through a click, which is a better design for touch devices. In that case `blur` doesn't apply. – Savage May 19 '17 at 07:30