DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

JavaScript and Media Queries: Building Responsive and Dynamic Web Applications

JavaScript and Media Queries: A Comprehensive Guide

Media queries are a powerful CSS feature used to apply styles based on the characteristics of the user's device, such as screen width, height, or resolution. JavaScript enhances the utility of media queries by enabling dynamic responses to changes in these conditions, providing greater control over how applications behave across different devices.


1. What Are Media Queries?

Media queries allow developers to define CSS rules that are applied conditionally, based on the properties of the user's device or viewport.

Basic Syntax in CSS:

@media (max-width: 768px) {
  body {
    background-color: lightblue;
  }
}
Enter fullscreen mode Exit fullscreen mode

With JavaScript, you can dynamically interact with these media queries using the Window.matchMedia() method.


2. Using JavaScript with Media Queries

The Window.matchMedia() method enables you to test a media query programmatically and respond to changes in real-time.

Syntax:

const mediaQuery = window.matchMedia("(max-width: 768px)");
Enter fullscreen mode Exit fullscreen mode

Check if the Query Matches:

if (mediaQuery.matches) {
  console.log("Viewport is 768px or smaller.");
} else {
  console.log("Viewport is larger than 768px.");
}
Enter fullscreen mode Exit fullscreen mode

3. Listening for Media Query Changes

You can use the addEventListener method to listen for changes in the media query state.

Example:

const mediaQuery = window.matchMedia("(max-width: 768px)");

function handleMediaQueryChange(e) {
  if (e.matches) {
    console.log("Now in mobile view.");
  } else {
    console.log("Now in desktop view.");
  }
}

// Attach listener
mediaQuery.addEventListener("change", handleMediaQueryChange);
Enter fullscreen mode Exit fullscreen mode

This approach dynamically responds to viewport changes without requiring a page reload.


4. Common Use Cases

a) Dynamic Layout Adjustments

Change JavaScript-driven layouts based on screen size.

const mediaQuery = window.matchMedia("(max-width: 768px)");

function adjustLayout() {
  if (mediaQuery.matches) {
    document.body.style.backgroundColor = "lightblue";
  } else {
    document.body.style.backgroundColor = "white";
  }
}

// Initial check and listener
adjustLayout();
mediaQuery.addEventListener("change", adjustLayout);
Enter fullscreen mode Exit fullscreen mode

b) Conditionally Loading Scripts

Load or execute scripts only when specific conditions are met.

const mediaQuery = window.matchMedia("(max-width: 768px)");

if (mediaQuery.matches) {
  // Load mobile-specific script
  import("./mobile.js").then(module => {
    module.init();
  });
}
Enter fullscreen mode Exit fullscreen mode

c) Adjusting Animations

Disable animations on smaller devices to improve performance.

const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");

if (mediaQuery.matches) {
  console.log("Reduce motion preferences detected.");
  document.body.classList.add("no-animations");
}
Enter fullscreen mode Exit fullscreen mode

5. Benefits of Combining JavaScript and Media Queries

  1. Dynamic Behavior: React to screen changes without reloading the page.
  2. Performance Optimization: Conditionally load resources or scripts.
  3. Enhanced Accessibility: Adapt to user preferences like reduced motion.
  4. Improved UX: Tailor interactions to different devices and viewports.

6. Best Practices

  • Combine CSS and JavaScript: Use CSS for styling and JavaScript for logic.
  • Debounce Resize Events: When responding to window resizes, debounce the event to avoid performance issues.
  • Fallbacks: Always include default behavior for unsupported browsers.
  • Use Modern Syntax: Prefer addEventListener over the deprecated addListener.

7. Browser Compatibility

Most modern browsers fully support the Window.matchMedia() API. However, older browsers may require polyfills for the addEventListener method on MediaQueryList.


8. Example: Responsive Navigation Menu

Here’s a practical example of combining media queries and JavaScript to manage a responsive menu.

const mediaQuery = window.matchMedia("(max-width: 768px)");
const navMenu = document.querySelector(".nav-menu");

function handleMenuBehavior() {
  if (mediaQuery.matches) {
    navMenu.classList.add("mobile-menu");
    console.log("Mobile menu applied.");
  } else {
    navMenu.classList.remove("mobile-menu");
    console.log("Desktop menu applied.");
  }
}

// Initial setup and listener
handleMenuBehavior();
mediaQuery.addEventListener("change", handleMenuBehavior);
Enter fullscreen mode Exit fullscreen mode

9. Conclusion

By combining JavaScript and media queries, you can achieve highly dynamic and responsive designs. This approach enables real-time adaptations to user preferences and device characteristics, enhancing both performance and user experience. Mastering these techniques is essential for building modern, device-friendly web applications.

Hi, I'm Abhay Singh Kathayat!
**I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: **kaashshorts28@gmail.com
.

Top comments (0)