javascriptretina

window.devicePixelRatio change listener


window.devicePixelRatio will return 1 or 2 depending on if I'm using my retina monitor or standard. If I drag the window between the two monitors, this property will change. Is there a way I can have a listener fire when the change occurs?


Solution

  • I took the IMO best answer (by @Neil) and made it a bit more human-readable:

    function listenOnDevicePixelRatio() {
      function onChange() {
        console.log("devicePixelRatio changed: " + window.devicePixelRatio);
        listenOnDevicePixelRatio();
      }
      matchMedia(
        `(resolution: ${window.devicePixelRatio}dppx)`
      ).addEventListener("change", onChange, { once: true });
    }
    listenOnDevicePixelRatio();
    

    No fixed boundary or variables needed.