One Byte Explainer: matchMedia
Andrew Bone

Andrew Bone @link2twenty

About: A British web developer, that is passionate about web accessibility.

Location:
Britain, Europe
Joined:
Jun 8, 2017

One Byte Explainer: matchMedia

Publish Date: Mar 20 '24
33 4

This is a submission for DEV Challenge v24.03.20, One Byte Explainer: Browser API or Feature.

Explainer

matchMedia, which exists on the window, is a method that facilitates checking CSS media queries in JavaScript. You can even use event listeners, with the change event, to detect media changes which can be super useful and, more importantly, cheap!

Additional Context

matchMedia is just so useful for those rare instances where media queries in CSS aren't enough and it's so much lighter than manually getting the size of the page and rechecking on every resize 😅.

Comments 4 total

  • pablojakub
    pablojakubMar 21, 2024

    What do you mean using change event in this context?
    document.addEventListener('change', () => {
    window.matchMedia('(max-width: 480px)') {
    // do something
    }
    })

    ?

    • Andrew Bone
      Andrew BoneMar 21, 2024

      Not quite you have to put the event listener on the returned matchMedia instance, like this.

      // set up the matchMedia instance
      const isSmall = window.matchMedia('(max-width: 480px)');
      
      // send true/false value off to some function to handle it
      someFunction(isSmall.matches) // this will be true/false depending on the media matching
      
      // set up a listener to detect media match changes
      isSmall.addEventListener('change', (event) => {
        // set the new true/false value to some function
        someFunction(event.matches);
      });
      
      Enter fullscreen mode Exit fullscreen mode

      Here's a quick example you can play with

      • pablojakub
        pablojakubMar 21, 2024

        Very nice :) Thank you. I suppose this is more optimal than window resize event ? :)

        • Andrew Bone
          Andrew BoneMar 21, 2024

          Very much so! It's why I love it so much it's fast and only fires when the media changes so no need to debounce.

Add comment