Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdown Javascript error: object doesn't support property or method 'matches'

I'm using the following JavaScript dropdown, which works perfect in all browers except the new Windows Edge.

It displays this error:

SCRIPT438: Object doesn't support property or method 'matches'

Script:

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

Got the script from: http://www.w3schools.com/howto/howto_js_dropdown.asp which I assumed would be compatible with all platforms. Now I've already implemented it, and ran into problems in Edge.

like image 589
Jones Avatar asked Apr 26 '16 08:04

Jones


1 Answers

It looks like you try to check if the click event was triggered by an object with the class dropbtn.

If you use jQuery you can do the same like this:

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

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!$(event.target).hasClass('dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

If you don't use jQuery you can get the className and then check if dropbtn is one of them.

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

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  var classes = event.target.className.split(' ');
  var found = false; var i = 0;
  while (i < classes.length && !found) {
      if (classes[i]=='dropbtn') found = true;
      else ++i;
  }
  if (!found) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
like image 188
Marc Compte Avatar answered Nov 15 '22 22:11

Marc Compte