If you want to add responsiveness to your website programmatically, you can use media queries with JavaScript. You can detect the current screen size and execute JavaScript code when the screen size changes.
The matchMedia()
method can be used to apply media queries in JavaScript for creating responsive websites. This method tests if a particular media query applies to the current viewport, and the addListener()
method can be used to set up a callback function that will be run whenever the media query's matches
value changes.
In this blog post, we will dive into the practical applications of media queries in JavaScript. So if you want to learn more about this topic, keep reading!
Use Media Queries in JavaScript With matchMedia()
The matchMedia()
method accepts a string. But you have to write this string in a specific format that we use in the CSS media query. To use this method, you first need to define the media query as a string, like "(min-width: 768px)"
.
Then you will call the matchMedia()
method and pass that string to it. It will return a MediaQueryList
object. Now we can use its properties and methods.
const mediaQuery = window.matchMedia('(min-width: 768px)')
// Check if the media query is true
if (mediaQuery.matches) {
// This code will run only if screen size is wider than 768px
console.log('Screen is wider than 768px')
}
The mediaQuery
object contains a matches
property. Using this property, we can verify whether the media query condition matches the current viewport.
In this example, this property will be true
if the current screen size is wider than 768px, otherwise false
. You can check and execute some code based on the screen size.
But you can do more with this object. The above code will only run once when JavaScript loads. It won't react if the screen size updates. You can easily do that by listening to the changes.
Also Read: Detect Device Orientation (Portrait/Landscape) in Javascript
Listen to Screen Size Changes For Different Devices
The MediaQueryList
object that we get from the mediaQuery()
method also has an addEventListener()
method. This method allows you to set up a callback function that will run whenever matches
value changes.
const mediaQuery = window.matchMedia('(min-width: 768px)')
// Listen to the change event
mediaQuery.addEventListener('change', (e) => {
if (e.matches) {
console.log('Screen is wider than 768px')
} else {
console.log('Screen is not wider than 768px')
}
})
Here I am using the addEventListener()
method and listening to the change
event. You can access the matches
property inside the callback function from the Event
object.
Now whenever the screen size changes and becomes wider than 768px, the e.matches
property will become true
. Due to this change, the callback function will run.
Again when the screen size becomes less than 768px, the e.matches
property will become false
. This change will also trigger the callback function.
This is useful for setting up a real-time response to viewport size changes. For example, you could use it to show or hide certain elements on the page, or to apply different styles depending on the screen size.
Also Read: How to Detect URL Hash Change in JavaScript (onhashchange)
Old Way to Use Media Queries in JavaScript
Earlier to do something based on the screen size, we had to listen to the resize
event on the window
object using the addEventListener()
method. The resize
event fires whenever the browser window size changes.
window.addEventListener('resize', () => {
if (window.innerWidth >= 768) {
console.log('Screen is wider than 768px')
} else {
console.log('Screen is not wider than 768px')
}
})
Every time we change the browser window size, the callback function will execute. We can check the value of window.innerWidth
property inside the callback function.
If it is greater than or equal to 768, the code inside the first if
block will be executed. But if it is less than 768, the code inside the else
block will be executed.
Window resize Event Listener vs. matchMedia Method
We have seen 2 techniques to use media queries with JavaScript. We have matchMedia()
method for this purpose. Before that, we had to use resize
event listener. Now the question is which technique you should use.
The answer is you should use matchMedia()
method to apply media queries. Because the technique has some limitations. These are:
- Lack of media query support: We don't have any specific way to test if a particular media query applies to the current viewport. But the
matchMedia()
method provides the matches property to verify this. - Get Triggered multiple times: The
resize
event executes the callback function for every pixel change. That means if a user increases or decreases the browser window size by 10px, the callback function will execute 10 times. In contrast, thechange
event of theMediaQueryList
object is only triggered when thematches
property value changes, which is more efficient. - Limited control over media queries: With this
window.addEventListener()
method, you have limited control over media queries. You can only apply styles or run scripts based on the width of the viewport. With thematchMedia()
method, you can define more complex media queries that take into account multiple dimensions and conditions.
Overall, the matchMedia()
method gives you a more efficient and flexible way to apply media queries using JavaScript to a web page, compared to using the resize
event.
Also Read: 3 Proven Methods to Create Multi-Line Strings in JavaScript
Conclusion
Media queries are an essential tool for creating a responsive website. That's why we use them in CSS while styling our websites. The matchMedia()
method gives us additional control over our web page layout.
Now with this method, you can test if a particular media query matches to the current viewport and perform actions based on the result.
You can also listen to the change
event to set up a callback function. This will allow you to update the page's content and layout in real time as the viewport changes.
I hope from this post and its examples, you have learned about this topic. Now, you can also use any CSS media queries with JavaScript on your websites.