Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript multiple media queries possible?

I'm looking into a way for JavaScript to understand more than one media queries. At this point I've the following code to check the width of the browser, but I want to create more queries. Google (and Stack) only showed me the code I've already written. The only way what I see is to use enquire.js, but I want to know if there isn't another way.

$(function() {
// Screen width check 
if (matchMedia) {
    var mq = window.matchMedia("(min-width: 992px)");
    mq.addListener(WidthChange);
    WidthChange(mq);
}

// Run function mq (check screen width)
function WidthChange(mq) {
    // Screen size +992px
    if (mq.matches) {
        .....
    }
    // Screen size -992px
    else {
        .....           
    }
// End widthChange(mq) function
}
// End Function script
});

So this code will only check for min-width: 992px, but now I want atleast 3 more.

like image 274
elJeffe Avatar asked Oct 31 '22 11:10

elJeffe


1 Answers

You can match multiple things by either having two (or more) query's or making a joint one.

Multiple query's

function screenIsWide() {
  var mq = window.matchMedia("(min-width: 992px)");
  return mq.matches;
}

function screenIsToWide() {
  var mq = window.matchMedia("(max-width: 9001px)");
  return mq.matches;
}

function isPrint() {
   var mq = window.matchMedia("print");
   return mq.matches;
}

console.log(screenIsWide() + " " + isPrint() + " " + screenIsToWide());

if(screenIsWide() && isPrint() && screenIsToWide()) {
   // do stuff
}

Joint

You can make this really easy just as in normal CSS Read more here w3schools.com

function isScreenAndIsWide() {
  var mq = window.matchMedia("screen and (min-width: 992px)");
  return mq.matches;
}

console.log(isScreenAndIsWide());
like image 177
arc Avatar answered Nov 09 '22 13:11

arc