0

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!";
}

}

SpikeThea
  • 340
  • 1
  • 3
  • 13

1 Answers1

1

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

Axnyff
  • 9,213
  • 4
  • 33
  • 37