How to Use Media Queries with JavaScript?
Last Updated :
13 Aug, 2024
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:
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:
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:
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.
Similar Reads
How to detect virtual keyboard using JavaScript ? This article, we are given an HTML document, the task is to detect a virtual keyboard if it pops up on the device's screen. A virtual keyboard is a tool that helps in the input of characters without the use of a physical keyboard. It is widely used in touchscreen devices.Approach: Unfortunately, the
2 min read
How to get Camera Resolution using JavaScript ? In this article, we will learn to find the maximum resolution supported by the camera. We need to request camera access from the user and once access is given we can check the resolution of the video stream and find out the resolution given by the camera. The .getUserMedia() method asks the user for
2 min read
How to detect when the window size is resized using JavaScript ? Sometimes when we develop our site, we want to detect the size of the window, In this article, we are going to learn how to detect when the window size is resized using JavaScriptThe window resize event occurs whenever the size of the browser window gets changed. We can listen to the resize event in
3 min read
How to get the image size (height & width) using JavaScript? To get the size of an image (height and width), Element.clientHeight and Element.clientWidth properties are used. Element.clientHeight: We can access the inner height of an element with this property. This height includes the padding but not the margin and border. Element.clientWidth: We can access
2 min read
How to find the width of a div using vanilla JavaScript? To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels. Below are the different approaches to finding the width of a div using vanilla JavaScrip
3 min read
How to open web cam in JavaScript ? In this article, we will see how to open a webcam and show a live video using JavaScript. For this, we are going to use Navigator Media Devices.Navigator Media DevicesIt is a read-only property that returns a Media Devices object, which helps us to access the connected media input devices like the c
2 min read