Skip to content

Media Query from JavaScript

Last updated on February 1, 2021

In this blog post, I would like to share with you on accessing Media Query from JavaScript.

We have mostly end up using Media Querieswithin CSS stylesheet for achieving responsive web design.

Introduction

Recently I was working on creating one Profile template markup where I had to switch sliding of the profiles automatically when mobile view but manual sliding for other view-ports.

In addition to the above point I have not used any fancy CSS frameworks/Library for designing this stuff but everything with Vanilla CSS, JS.

Media Query From JavaScript

While designing the above template markup, I thought of doing this within CSS style-sheet for recognizing various viewport sizes with Media Query

But doing so I felt adding/removing classes within CSS wouldn’t be possible, so I turned up to JavaScript. That’s what I am going to here share with you How we can access media query from JavaScript.

To be effective of this post, I will walk you through step by step.

First of all, we should identify which are all view port size that we want to target

Here I require particularly mobile & desktop version such as @media only screen and (min-width : 768px) { } and @media only screen and (max-width : 767px) { }respectively.

If you already saw one of my previous blog post where I have written Minimally required Media-Queriesthen this would be more familiar for you since the same I have done it from JavaScript end.

// Media Queries
const mobilePortraitVp = 'only screen and (min-width : 320px)';
const mobileLandscapeVp = 'only screen and (min-width : 480px)';
const tabletVp = 'only screen and (max-width : 767px)';
const tabletLandscapeVp = 'only screen and (min-width: 768px)';
const desktopVp = 'only screen and (min-width : 992px)';
const largeVp = 'only screen and (min-width : 1200px)';

Once after defined the required view ports, we will have to use the predefined function called matches from the WindowObject.

const mql = window.matchMedia(tabletVp);

Note: In my case, I need tabletVpview port variable as we need to switch only when mobile view hits.

The defined mqlvariable exposes an event-listener that will get called once when tablet view port hits.

// Media Query
mql.addEventListener("change", (e) => {
    if (e.matches) {
    /* the viewport is 767 pixels wide or less */
    console.log('This is less than 767px wide.');
  } else {
    /* the viewport is more than than 767 pixels wide */
    console.log('This is more than 767px wide.')
  }
});

In this way, you can handle your DOM manipulation for styling based on media query through JavaScript.

If you’re curious to see it in action then grab the above said template from my codepen.

Published inAngularFrameworksJavaScriptReact