41

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 that I can use Javascript (not jQuery) to dynamically add or remove a class to the to represent the two different sizes and then recode this something like:

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

If this works then can someone comment as to if using Javascript is a better way to do this?

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

1 Answers1

86

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

for example

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

Please refer the below links for better understanding

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

Updated as per comment

Please refer the plunker: "http://plnkr.co/edit/wAKFEFz0NU6ZaEmywlgc?p=preview"

For better understanding: "http://www.javascriptkit.com/javatutors/matchmediamultiple.shtml"

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

typeoneerror
  • 55,990
  • 32
  • 132
  • 223
sahil gupta
  • 2,339
  • 12
  • 14
  • I am a bit confused. Can you give an example with say for example the width of a
    is set to 100px when the window is less than 500 px and 150px when the window is less than 600 px. Would this be able to change the width of the
    dynamically as I resize the window. Also is this something that would work on all modern browsers?
    – Samantha J T Star Jul 22 '15 at 11:46
  • @SamanthaJ : Updated the answer!! – sahil gupta Jul 23 '15 at 06:33