Is there any javascript equivalent to using @media request?

I have this code:

@media screen and (max-width: 570px) {

    #header {
        .flex-wrap(wrap);
        .justify-content(center);

        #headerTitles {
            margin-top: 1rem;
        }

    }
}

@media screen and (min-width: 571px) and (max-width: 950px) {

    #header.authenticated {
        .flex-wrap(wrap);
        .justify-content(center);

        #headerTitles {
            margin-top: 2rem;
        }
    }

}

Is there a way I can use Javascript (not jQuery) to dynamically add or remove a class to represent two different sizes, and then transcode it something like this:

.small #headerTitles { margin-top: 1rem; }
.large #headerTitles { margin-top: 2rem; }

If this works, can anyone comment if using Javascript is the best way to do this?

+4
source share
1 answer

You can use window.matchMedia()for media queries in javascript.

eg

var mq = window.matchMedia( "(max-width: 570px)" );
if (mq.matches) {
    // window width is at less than 500px
}
else {
    // window width is greater than 500px
}

Please refer to the links below for a better understanding.

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia http://www.sitepoint.com/javascript-media-queries/

, : " http://plnkr.co/edit/wAKFEFz0NU6ZaEmywlgc?p=preview"

: http://www.javascriptkit.com/javatutors/matchmediamultiple.shtml"

-: " https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/ "

+20

Source: https://habr.com/ru/post/1598651/


All Articles