Checking Media Queries With Javascript

Legacy Content Notice: This post demonstrates jQuery and ES5 JavaScript patterns from 2014. For modern media query detection with vanilla JavaScript and contemporary APIs, see our Modern JavaScript Development Guide.

With the web being used on so many different devices now it's very important that you can change your design to fit on different screen sizes. The best way of changing your display depending on screen size is to use media queries to find out the size viewport of the screen and allowing you to change the design depending on what screen size is on. You will mainly make these changes in the CSS file as you can define the media query break points to change the design on different devices like this.


/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {

}

/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {

}

/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {

}

The above code will allow you to make styling completely different on different devices, but what if you wanted to change the functionality of the site depending on the screen size? What if you needed to use some Javascript code on different screen sizes, for example to create a slide down navigation button.

How Do You Use Media Queries With jQuery

Media queries will be checking the width of the window to see what the size of the device is so you would think that you can use a method like .width() on the window object like this.


if($(window).width() < 767)
{
   // change functionality for smaller screens
} else {
   // change functionality for larger screens
}

But this will not return the true value of the window as it takes into effect things like body padding and scroll bars on the window. The other option you have when checking the media size is to use a Javascript method of .matchMedia() on the window object.


var window_size = window.matchMedia('(max-width: 768px)'));

This works the same way as media queries and is supported on many browsers apart from IE9 and lower. Can I Use window.matchMedia To use matchMedia you need to pass in the min or max values you want to check (like media queries) and see if the viewport matches this.


if (window.matchMedia('(max-width: 768px)').matches)
{
    // do functionality on screens smaller than 768px
}

Now you can use this to add a click event on to a sub-menu for screens smaller than 768px. The below code is an example of how you can add some Javascript code which will only be run on screens smaller than 768px.


if (window.matchMedia('(max-width: 768px)').matches)
{
    $('.sub-menu-button').on('click', function(e)
    {
        var subMenu = $(this).next('.sub-navigation');
        if(subMenu.is(':visible'))
        {
            subMenu.slideUp();
        } else {
            subMenu.slideDown();
        }

        return false;
    });
}

Modern JavaScript Approaches (2024)

Here's how to handle responsive JavaScript functionality using modern APIs and patterns:

Modern: Using ResizeObserver API

// Modern responsive behavior with ResizeObserver
class ResponsiveHandler {
    constructor() {
        this.breakpoints = {
            mobile: 768,
            tablet: 1024,
            desktop: 1200,
        };

        this.init();
    }

    init() {
        // Use ResizeObserver for efficient resize handling
        this.observer = new ResizeObserver((entries) => {
            this.handleResize();
        });

        this.observer.observe(document.body);
        this.handleResize(); // Initial check
    }

    getCurrentBreakpoint() {
        const width = window.innerWidth;

        if (width < this.breakpoints.mobile) return "mobile";
        if (width < this.breakpoints.tablet) return "tablet";
        if (width < this.breakpoints.desktop) return "desktop";
        return "large";
    }

    handleResize() {
        const breakpoint = this.getCurrentBreakpoint();
        this.updateNavigation(breakpoint);
    }

    updateNavigation(breakpoint) {
        const nav = document.querySelector(".navigation");
        const menuButton = document.querySelector(".menu-button");

        if (breakpoint === "mobile") {
            this.enableMobileMenu();
        } else {
            this.disableMobileMenu();
        }
    }

    enableMobileMenu() {
        const menuButton = document.querySelector(".menu-button");
        const subMenu = document.querySelector(".sub-navigation");

        if (!menuButton.dataset.listenerAdded) {
            menuButton.addEventListener("click", this.toggleSubMenu.bind(this));
            menuButton.dataset.listenerAdded = "true";
        }
    }

    disableMobileMenu() {
        const subMenu = document.querySelector(".sub-navigation");
        if (subMenu) {
            subMenu.style.display = ""; // Reset to CSS default
        }
    }

    toggleSubMenu(event) {
        event.preventDefault();
        const subMenu = document.querySelector(".sub-navigation");

        if (subMenu.style.display === "none" || !subMenu.style.display) {
            subMenu.style.display = "block";
        } else {
            subMenu.style.display = "none";
        }
    }
}

// Initialize when DOM is loaded
document.addEventListener("DOMContentLoaded", () => {
    new ResponsiveHandler();
});

Modern: Using CSS Custom Properties and matchMedia

// Modern approach using CSS custom properties
class ModernResponsive {
    constructor() {
        this.mediaQueries = new Map([
            ["mobile", window.matchMedia("(max-width: 767px)")],
            [
                "tablet",
                window.matchMedia("(min-width: 768px) and (max-width: 1023px)"),
            ],
            ["desktop", window.matchMedia("(min-width: 1024px)")],
        ]);

        this.init();
    }

    init() {
        // Set up listeners for each breakpoint
        this.mediaQueries.forEach((mq, name) => {
            mq.addEventListener("change", () =>
                this.handleBreakpointChange(name, mq)
            );

            // Check initial state
            if (mq.matches) {
                this.handleBreakpointChange(name, mq);
            }
        });
    }

    handleBreakpointChange(breakpoint, mediaQuery) {
        if (mediaQuery.matches) {
            document.documentElement.dataset.breakpoint = breakpoint;
            this.updateForBreakpoint(breakpoint);
        }
    }

    updateForBreakpoint(breakpoint) {
        switch (breakpoint) {
            case "mobile":
                this.enableMobileFeatures();
                break;
            case "tablet":
                this.enableTabletFeatures();
                break;
            case "desktop":
                this.enableDesktopFeatures();
                break;
        }
    }

    enableMobileFeatures() {
        // Mobile-specific functionality
        console.log("Mobile layout active");
    }

    enableTabletFeatures() {
        // Tablet-specific functionality
        console.log("Tablet layout active");
    }

    enableDesktopFeatures() {
        // Desktop-specific functionality
        console.log("Desktop layout active");
    }
}

new ModernResponsive();

Modern: Container Queries (2024)

/* Modern CSS Container Queries */
.navigation {
    container-type: inline-size;
}

@container (max-width: 768px) {
    .sub-navigation {
        display: none;
    }

    .menu-button {
        display: block;
    }
}
// JavaScript to work with container queries
if ("container" in document.documentElement.style) {
    // Container queries are supported
    console.log("Using container queries for responsive behavior");
} else {
    // Fallback to traditional media queries
    console.log("Falling back to media queries");
}

This post demonstrates legacy JavaScript patterns and is preserved for historical reference. Modern development favors ResizeObserver, Container Queries, and modern APIs for responsive functionality.