Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to use media queries with JavaScript?
JavaScript provides the window.matchMedia() method to detect and respond to CSS media query changes dynamically. This allows you to create responsive behavior that adapts to screen size, device orientation, and other media features.
Basic Syntax
let mediaQuery = window.matchMedia("(max-width: 768px)");
// Check if query matches
if (mediaQuery.matches) {
// Screen is 768px or smaller
}
// Listen for changes
mediaQuery.addEventListener('change', function(e) {
if (e.matches) {
// Query now matches
}
});
Example: Responsive Background Color
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
color: white;
padding: 20px;
transition: background-color 0.3s ease;
}
</style>
</head>
<body>
<h1>Using Media Queries with JavaScript</h1>
<h2>Resize the screen to see the color change from blue to red</h2>
<p id="status">Current screen width: Large (Blue)</p>
<script>
var mediaQuery = window.matchMedia("(max-width: 700px)");
var statusElement = document.getElementById("status");
function setColor(mediaQuery) {
if (mediaQuery.matches) {
document.body.style.backgroundColor = "red";
statusElement.textContent = "Current screen width: Small (Red)";
} else {
document.body.style.backgroundColor = "blue";
statusElement.textContent = "Current screen width: Large (Blue)";
}
}
// Set initial color
setColor(mediaQuery);
// Listen for changes
mediaQuery.addEventListener('change', setColor);
</script>
</body>
</html>
Multiple Media Queries
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
text-align: center;
}
.device-info {
font-size: 18px;
font-weight: bold;
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Multiple Media Queries</h1>
<div class="device-info" id="deviceType">Device: Desktop</div>
<script>
// Define multiple breakpoints
const queries = {
mobile: window.matchMedia("(max-width: 480px)"),
tablet: window.matchMedia("(min-width: 481px) and (max-width: 768px)"),
desktop: window.matchMedia("(min-width: 769px)")
};
const deviceElement = document.getElementById("deviceType");
function updateDevice() {
if (queries.mobile.matches) {
deviceElement.textContent = "Device: Mobile Phone";
document.body.style.backgroundColor = "#ff6b6b";
} else if (queries.tablet.matches) {
deviceElement.textContent = "Device: Tablet";
document.body.style.backgroundColor = "#4ecdc4";
} else if (queries.desktop.matches) {
deviceElement.textContent = "Device: Desktop";
document.body.style.backgroundColor = "#45b7d1";
}
}
// Set initial state
updateDevice();
// Add listeners for all queries
Object.values(queries).forEach(query => {
query.addEventListener('change', updateDevice);
});
</script>
</body>
</html>
Common Media Query Types
| Query Type | Example | Use Case |
|---|---|---|
| Width | (max-width: 768px) |
Responsive breakpoints |
| Orientation | (orientation: portrait) |
Device rotation |
| Hover | (hover: hover) |
Touch vs mouse devices |
| Dark Mode | (prefers-color-scheme: dark) |
System theme preference |
Dark Mode Detection Example
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
transition: all 0.3s ease;
}
.light-theme {
background-color: white;
color: black;
}
.dark-theme {
background-color: #2d2d2d;
color: white;
}
</style>
</head>
<body>
<h1>Dark Mode Detection</h1>
<p id="themeStatus">Theme: Light</p>
<script>
const darkModeQuery = window.matchMedia("(prefers-color-scheme: dark)");
const statusElement = document.getElementById("themeStatus");
function updateTheme(e) {
if (e.matches) {
document.body.className = "dark-theme";
statusElement.textContent = "Theme: Dark (System Preference)";
} else {
document.body.className = "light-theme";
statusElement.textContent = "Theme: Light (System Preference)";
}
}
// Set initial theme
updateTheme(darkModeQuery);
// Listen for theme changes
darkModeQuery.addEventListener('change', updateTheme);
</script>
</body>
</html>
Key Methods and Properties
-
matchMedia(query)- Creates a MediaQueryList object -
.matches- Boolean indicating if query currently matches -
.addEventListener('change', callback)- Modern way to listen for changes -
.removeEventListener('change', callback)- Remove change listener
Conclusion
JavaScript media queries with window.matchMedia() enable dynamic responsive behavior beyond CSS capabilities. Use them to create adaptive user interfaces that respond to screen size, device capabilities, and user preferences in real-time.
Advertisements
