DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Watch CSS3 Media Queries in JavaScript

CSS3's media queries are an essential element of responsive web design.

Here's a simple media query example that increases the font size on screens with larger widths:

p {
    font-size: 14px;
}
@media screen and (min-width: 768px) {
    p {
        font-size: 18px;
    }
}
Enter fullscreen mode Exit fullscreen mode

While media queries provide a handy way for responsively updating CSS values, you might also want to perform certain actions based on the current screen width using JavaScript as well.

This is a snippet that recreates the above CSS example in JavaScript:

const update = (mediaQuery) => 
    !!mediaQuery.matches
        ? document.querySelectorAll(`p`).fontSize = `18px`
        : document.querySelectorAll(`p`).fontSize = `16px`;

const query = window.matchMedia(`screen and (min-width: 768px)`);

update(query);
Enter fullscreen mode Exit fullscreen mode

You can also listen for changes to query:

query.addListener(update);
Enter fullscreen mode Exit fullscreen mode

And you can of course include whatever code you want in the update function, and you can pass any other kind of valid media query to it as well. This is just an example.

Getting the current screen dimensions

If you just want to get the dimensions of the browser window in JavaScript, there is a better way:

const width = window.screen.width;

const height = window.screen.height;
Enter fullscreen mode Exit fullscreen mode

The above code will return the integer value of the screen width and height, in pixels. However, the returned values won't automatically update each time the screen is resized.

Conclusion

Anyway, I hope you found this quick little snippet useful!

It's great for running a function each time the screen is resized, among other things.

Top comments (0)