Subscribe

Getting notified in JavaScript when a Media Query changes

โœ๏ธ

Did you know JavaScript also support Media Queries?

29 Aug, 2020 ยท 2 min read

Media queries are fantastic and well used in modern web development. But how can one notify JavaScript if a particular media query is met.

There is a window listener called: matchMedia, which does precisely this!

This is what we will be making today:

JavaScript Media Query Changes

To use matchMedia, we call the following:

const mediaQuery = window.matchMedia('(max-width: 500px)');

To use it we can add listeners to it:

mediaQuery.addListener(console.log);

If we size our screen with the console open, it will fire a console log for each this media queries matches.

The return will have a MediaQueryListEvent, which contains a value called matches to say true or false.

Console logs are cool, but it doesn't do much for us, so we can also attach a function:

mediaQuery.addListener(alertMe);

function alertMe(e) {
  if (e.matches) {
    document.body.style.backgroundColor = 'green';
  } else {
    document.body.style.backgroundColor = 'red';
  }
}

If we resize and hit the media query, our screen will turn green or red depending on yes or no.

See this Codepen for a demo.

See the Pen Getting notified in JavaScript when a Media Query changes by Chris Bongers (@rebelchris) on CodePen.

More on MediaQueryList here MDN Web Docs

Browser Support

This function has outstanding support! For a novice function, one to use in projects.

MediaQueryList support

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

TypeORM viewEntity

30 Mar, 2022 ยท 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 ยท 3 min read

The Record Utility Type in TypeScript

Join 1371 devs and subscribe to my newsletter