Debugging event bubbling errors with vanilla JS
This week, Kieran Barker messaged me about a console error he was getting on a project he was working on.
Uncaught TypeError: event.target.matches is not a function at HTMLDocument.<anonymous>
He was using event delegation with the matches()
method to detect hover events. And here’s an example of the type of code that was triggering that error.
document.addEventListener('mouseenter', function (event) {
if (event.target.matches('button')) {
console.log('Found the button!');
}
}, true);
You can play with this yourself in this CodePen.
Any idea what’s going on here? Kieran was kind enough to let me do a live debugging session with him and record it. Here’s the walk-through.
The short version: the event was also detecting hover events on the parent document
object, which has no matches()
method.
To prevent the error, he added a check to make sure matches()
is supported by the element before trying to use it.
document.addEventListener('mouseenter', function (event) {
// Make sure it's not the document object
if (!('matches' in event.target)) return;
// Do your thing...
if (event.target.matches('button')) {
console.log('Found the button!');
}
}, true);