I'm trying to use the window.matchMedia event listener to detect if the user is on a touch device or not. But im just seems to be only activate when the chrome DevTools window is resized, and not actually detect if it is a touch device (for example, on my pixel 3a).
here is the code i used for the event listener
if (matchMedia) {
let mql = window.matchMedia('(pointer: fine)');
mql.addListener(touchChange)
}
and the function which it runs
function touchChange (event) {
if (event.matches) {
touchcontrols = true;
console.log("Touch Controls");
console.log(window.innerWidth);
document.getElementById("lives").innerHTML = "Touch Events!";
}
}
If you just want to see if it matches once you can use:
let matches = window.matchMedia('(pointer: fine)').matches;
window.matchMedia
returns an object with a matches
property which indicates if it's currently matching your query and an addListener
to register a callback which will be called in response to the media query status changing.
More on this: https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener