Open In App

How to Use Media Queries with JavaScript?

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Media queries are a useful tool in CSS that allows us to apply styles based on the size of the viewport or other device characteristics. However, there are times when we might need to handle media queries directly in JavaScript. This can be useful for making our website more interactive or for applying specific JavaScript logic based on the screen size. In this article, we are going to discuss how we can use media queries with JavaScript, different approaches, and code examples.

Media queries let us change the appearance of our website based on the device it's being viewed on. While CSS handles most of the styling, JavaScript can be used when we need to make dynamic changes or trigger specific functions depending on the viewport size.

Below are different ways we can use media queries in JavaScript:

Using window.matchMedia()

The window.matchMedia() method allows you to evaluate a media query directly in JavaScript. It returns a MediaQueryList object that tells you whether the document currently matches the media query.

Syntax:

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

Example: Below is an example code, where we check if the viewport width is 600 pixels or less and then log a message to the console.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <title>Media Queries with JavaScript</title>
</head>

<body>

    <script>
        const mediaQuery = window.matchMedia('(max-width: 600px)');

        if (mediaQuery.matches) {
            console.log('Viewport is 600px or less');
        } else {
            console.log('Viewport is greater than 600px');
        }
    </script>

</body>

</html>

Output:

Using Event Listeners for Media Query Changes

We can also set up an event listener to respond to changes in the media query. This is useful if we want to trigger some JavaScript code when the user resizes the browser window.

Syntax:

mediaQuery.addListener(callbackFunction);

Example: Let's use the previous example to include an event listener that detects when the viewport size changes.Here, the handleTabletChange function runs whenever the viewport changes and matches the specified media query. Using this way, we can react to the viewport resizing in real-time.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <title>Responsive JavaScript</title>
</head>

<body>

    <script>
        const mediaQuery = window.matchMedia('(max-width: 600px)');

        function handleTabletChange(e) {
            if (e.matches) {
                console.log('Viewport is now 600px or less');
            } else {
                console.log('Viewport is now greater than 600px');
            }
        }

        // Register event listener
        mediaQuery.addListener(handleTabletChange);

        // Initial check
        handleTabletChange(mediaQuery);
    </script>

</body>

</html>

Output:

Handling Multiple Media Queries

Sometimes, you might need to handle multiple media queries in your JavaScript. You can easily achieve this by creating multiple window.matchMedia() objects and handling them accordingly.

Syntax:

const mediaQuery1 = window.matchMedia('(max-width: 600px)');
const mediaQuery2 = window.matchMedia('(max-width: 1200px)');

Example: This demonstrates the screen size and logs different messages depending on whether the screen is small, medium, or large.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, 
                   initial-scale=1.0">
    <title>Multiple Media Queries</title>
</head>

<body>

    <script>
        const smallScreen =
            window.matchMedia('(max-width: 600px)');
        const mediumScreen =
            window.matchMedia('(min-width: 601px) and (max-width: 1200px)');

        function handleScreenChange() {
            if (smallScreen.matches) {
                console.log('Small screen');
            } else if (mediumScreen.matches) {
                console.log('Medium screen');
            } else {
                console.log('Large screen');
            }
        }

        smallScreen.addListener(handleScreenChange);
        mediumScreen.addListener(handleScreenChange);

        // Initial check
        handleScreenChange();
    </script>

</body>

</html>

Output:

Conclusion

Using media queries in JavaScript allows us to create more responsive and interactive websites by dynamically changing the behavior based on the screen size. Whether we are using window.matchMedia() for simple checks or adding event listeners for real-time responsiveness, these techniques can enhance our site's user experience.


Next Article

Similar Reads