How to use Media Query in Javascript?

To make webpage responsive we use lots of media queries. Actually, Media Queries are a CSS feature that allows us to apply different screen width rules to our CSS. In many adaptive application we need to write JavaScript code which supports many devices. But these Media Queries in CSS what about in JavaScript? Can I use it in JavaScript? If yes, then how can I use Media Query in JavaScript?.

Well, now it is possible to use media query in JavaScript with the help of the window.matchMedia function. It is well supported and if you don’t need to support IE8 or lower you may use it without worry. Browser Support for window.matchMedia() is also pretty good.


var mql = window.matchMedia("screen and (min-width: 800px)")
if (mql.matches){ // if media query matches
 alert("Window is 800px or wider")
 // do something else


window.matchMedia() returned properties
Property Description
matches Boolean that returns true if the current state of the
window matches the conditions defined in the CSS query string, or false
if not.
media Returns the serialized media query list. In the case of
the operation:

var mql = window.matchMedia(“screen
and (max-width: 765px)”) would return:

“screen and (max-width: 765px)”

Events / Methods

window.matchMedia() returned methods/ event handlers
method Description
addListener( functionref) Adds a new listener function, which is executed whenever
the state of the window changes and triggers a re-evaluation of the
defined CSS media query.
removeListener(functionref) Removes a previously added listener function from
listening in on changes between the current state and the defined CSS
media query.

The following code uses addListener() to react to a CSS media query not just on run time, but also when any changes to the window state occur:

function mediaqueryresponse(mql){
    if (mql.matches){ // if media query matches
      console.log("The condition " + + " has been met")
      console.log("Condition not met yet")

var mql = window.matchMedia("screen and (max-device-width: 480px) and (orientation: portrait)")
mediaqueryresponse(mql) // call listener function explicitly at run time
mql.addListener(mediaqueryresponse) // attach listener function to listen in on state changes

Now we have all the pieces in JavaScript to respond to a CSS media query. For more details on matchMedia please click here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s