2

I'm getting an error in IE:

Object doesn't support property or method 'matches'".

Tried to close the dropdown list when clicking outside.

Below is the code:

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    var openDropdown = dropdowns[i];
    if (openDropdown.classList.contains('show')) {
      openDropdown.classList.remove('show');
    }
  }
}
<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Options</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#directory" class="directory">Content Directory</a>
    <a href="#objective" class="objective">Objectives</a>
    <a href="#reference" class="reference">Reference</a>
    <a href="#help" class="help">Help</a>
  </div>
</div>
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
arun
  • 21
  • 4

2 Answers2

0

See answer at https://stackoverflow.com/a/34994338/746984

$(document).click(function(event) { 
    if(!$(event.target).closest('#myDropdown').length) {
        if($('#myDropdown').is(":visible")) {
            $('#myDropdown').hide();
        }
    }        
});

Worked for me. I've also messaged w3schools, who provided the original example that has the issue.

Community
  • 1
  • 1
Savage
  • 2,296
  • 2
  • 30
  • 40
0

I spent a good 15 minutes trying to figure it out.

Use the same code but change .matches to .contains and get rid of that exclamation point.

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

window.onclick = function (event) {
  if (event.target.contains(".dropbtn")) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    var openDropdown = dropdowns[i];
    if (openDropdown.classList.contains("show")) {
      openDropdown.classList.remove("show");
    }
  }
};

This should fix all your problems without all the confusion.

mrmowji
  • 934
  • 8
  • 29