Sign in
Log inSign up

Watch CSS3 Media Queries in JavaScript

Nathan's photo
Nathan
·Sep 25, 2021·

2 min read

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

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);

You can also listen for changes to query:

query.addListener(update);

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;

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.

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct