Javascript dropdown error: object does not support property or method 'matches'

I use the following JavaScript drop-down menu that works fine in all browsers except the new Windows Edge.

Displays this error:

SCRIPT438: object does not support 'matches' properties or methods

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 a script from: http://www.w3schools.com/howto/howto_js_dropdown.asp , which I assumed would be compatible with all platforms. Now I already implemented it and ran into problems in Edge.

+5
source share
3 answers

It looks like you're trying to check if the click event raised an object with the dropbtn class.

If you use jQuery, you can do the same:

 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 are not using jQuery, you can get the class name 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'); } } } } 
+7
source

According to http://caniuse.com/#search=matches EDGE has partial support with the prefix 'ms'.

+1
source

For a cross-browser solution, see http://youmightnotneedjquery.com/#matches_selector

 var matches = function(el, selector) { return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector); }; matches(el, '.my-class'); 
+1
source

Source: https://habr.com/ru/post/1247918/


All Articles