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.
4 Answers 4
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');
}
}
}
}
1 Comment
As it was mentioned before IE11 has partial support for it. Try this
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector;
}
Comments
For a cross-browser solution, look at 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');
Comments
According to http://caniuse.com/#search=matches EDGE has partial support with the prefix 'ms'.
Comments
Explore related questions
See similar questions with these tags.