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?
Best Answer
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/matchMediahttp://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/"