JavaScript Window matchMedia() Method: Matching Media Queries

February 7, 2025

JavaScript Window matchMedia() Method: Matching Media Queries

The window.matchMedia() method in JavaScript is a powerful tool that enables developers to programmatically access and evaluate CSS media queries. This functionality is especially valuable for creating responsive web applications, allowing JavaScript code to adapt the behavior of a web page based on the characteristics of the device or browser environment.

Purpose of matchMedia()

The primary purpose of window.matchMedia() is to allow JavaScript code to:

  • Dynamically check the state of CSS media queries.
  • Implement conditional logic based on the device’s screen size, orientation, resolution, or other media features.
  • Create responsive and adaptive web experiences.

Syntax of matchMedia()

The syntax for using the matchMedia() method is as follows:

const mediaQueryList = window.matchMedia(mediaQueryString);

Parameters:

  • mediaQueryString: A string representing a CSS media query.

Return Value:

  • A MediaQueryList object, which provides information about the media query, including whether it currently matches the browsing context.

MediaQueryList Object Properties

The MediaQueryList object returned by window.matchMedia() has the following key properties:

Property Type Description
`media` String The media query string that was used to create the `MediaQueryList` object.
`matches` Boolean Indicates whether the media query currently matches the browsing context. Returns `true` if it matches, and `false` if it doesn’t.
`onchange` Function An event handler that is called when the state of the media query changes (i.e., when it starts or stops matching). This is now largely superseded by the addEventListener() method.

Examples of Using matchMedia()

Let’s explore some practical examples of how to use the window.matchMedia() method in JavaScript.

Basic Media Query Matching

This example demonstrates how to check if the screen width is less than 768 pixels and display a message accordingly.

<!DOCTYPE html>
<html>
<head>
    <title>matchMedia Basic Example</title>
</head>
<body>
    <div id="message1"></div>

    <script>
        const mediaQueryList1 = window.matchMedia("(max-width: 768px)");
        const messageDiv1 = document.getElementById("message1");

        if (mediaQueryList1.matches) {
            messageDiv1.textContent = "Screen width is less than 768px";
        } else {
            messageDiv1.textContent = "Screen width is 768px or more";
        }
    </script>
</body>
</html>

This code checks whether the media query (max-width: 768px) matches the current window size. If the screen width is less than or equal to 768 pixels, it displays a message indicating that the screen is small.

Adding and Removing Event Listeners

This example shows how to add an event listener to the MediaQueryList object to detect changes in the media query state and update the content dynamically.

<!DOCTYPE html>
<html>
<head>
    <title>matchMedia Event Listener Example</title>
</head>
<body>
    <div id="message2"></div>

    <script>
        const mediaQueryList2 = window.matchMedia("(max-width: 768px)");
        const messageDiv2 = document.getElementById("message2");

        function handleMediaChange2(event) {
            if (event.matches) {
                messageDiv2.textContent = "Screen width is less than 768px";
            } else {
                messageDiv2.textContent = "Screen width is 768px or more";
            }
        }

        mediaQueryList2.addEventListener("change", handleMediaChange2);

        // Initial check
        handleMediaChange2(mediaQueryList2);
    </script>
</body>
</html>

In this example, an event listener is added to the MediaQueryList object. Whenever the media query state changes (i.e., when the screen width crosses the 768px threshold), the handleMediaChange function is called to update the message accordingly.

Dynamically Modifying Styles

Here’s an example of how to dynamically modify the styles of an element based on the media query state.

<!DOCTYPE html>
<html>
<head>
    <title>matchMedia Dynamic Style Example</title>
    <style>
        #box3 {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="box3"></div>

    <script>
        const mediaQueryList3 = window.matchMedia("(max-width: 768px)");
        const box3 = document.getElementById("box3");

        function handleMediaChange3(event) {
            if (event.matches) {
                box3.style.backgroundColor = "blue";
            } else {
                box3.style.backgroundColor = "red";
            }
        }

        mediaQueryList3.addEventListener("change", handleMediaChange3);

        // Initial check
        handleMediaChange3(mediaQueryList3);
    </script>
</body>
</html>

This code changes the background color of a div element based on the screen width. If the screen width is less than 768 pixels, the background color becomes blue; otherwise, it remains red.

Use with addEventListener Options

You can use addEventListener options such as once and passive with matchMedia.

<!DOCTYPE html>
<html>
<head>
    <title>matchMedia addEventListener Options Example</title>
</head>
<body>
    <div id="message4"></div>

    <script>
        const mediaQueryList4 = window.matchMedia("(max-width: 768px)");
        const messageDiv4 = document.getElementById("message4");

        function handleMediaChange4(event) {
            messageDiv4.textContent = event.matches ? "Matched" : "Not Matched";
        }

        mediaQueryList4.addEventListener("change", handleMediaChange4, { once: true });

        // Initial check
        handleMediaChange4(mediaQueryList4);
    </script>
</body>
</html>

In this example, the event listener is set to run only once using the once: true option.

Removing Event Listeners

Here’s how to remove an event listener from a MediaQueryList:

<!DOCTYPE html>
<html>
<head>
    <title>matchMedia Remove Event Listener Example</title>
</head>
<body>
    <div id="message5"></div>

    <script>
        const mediaQueryList5 = window.matchMedia("(max-width: 768px)");
        const messageDiv5 = document.getElementById("message5");

        function handleMediaChange5(event) {
            messageDiv5.textContent = event.matches ? "Matched" : "Not Matched";
        }

        mediaQueryList5.addEventListener("change", handleMediaChange5);

        // Remove the event listener after 5 seconds
        setTimeout(() => {
            mediaQueryList5.removeEventListener("change", handleMediaChange5);
            messageDiv5.textContent = "Event listener removed";
        }, 5000);

        // Initial check
        handleMediaChange5(mediaQueryList5);
    </script>
</body>
</html>

This code adds and then removes the event listener after 5 seconds, demonstrating how to clean up event listeners when they are no longer needed.

Practical Applications

The window.matchMedia() method is invaluable in a variety of scenarios:

  1. Responsive Navigation Menus: Dynamically switch between a full navigation menu and a hamburger menu based on screen size.
  2. Adaptive Images: Load different image sizes or resolutions based on the device’s screen resolution.
  3. Conditional Script Loading: Load or execute different JavaScript code based on media query conditions.
  4. Dynamic UI Components: Adjust the layout and styling of UI components based on the device’s orientation (portrait or landscape).

Browser Support

The window.matchMedia() method is widely supported across modern web browsers, including:

  • Chrome
  • Firefox
  • Safari
  • Edge
  • Opera

Tips and Best Practices

  • Use Debouncing: When responding to frequent media query changes (e.g., during window resizing), use debouncing to avoid excessive calculations and updates.
  • Consider Performance: Avoid complex or computationally intensive operations within media query event handlers to ensure smooth performance.
  • Test Across Devices: Thoroughly test your responsive designs across a variety of devices and screen sizes to ensure a consistent user experience.

Conclusion

The window.matchMedia() method is a powerful and versatile tool for creating responsive web applications that adapt to different device characteristics. By leveraging this method, developers can dynamically adjust the behavior and styling of web pages to provide optimal user experiences across a wide range of devices and screen sizes.