2

Let's say I have multiple CSS style sheets which apply at different resolutions with media queries, how do you detect which CSS stylesheets are currently active and being used with JavaScript OR jQuery?

Thanks :)

5
  • what exactly are you needing to do? Commented Jan 27, 2016 at 1:27
  • Just when the page loads, detect which stylesheets are active on the page based on min-width and max-width and which ones are being ignored. Commented Jan 27, 2016 at 1:48
  • right...that's just stating what's in the question, not the higher level use case. What problem are you trying to solve? Commented Jan 27, 2016 at 1:55
  • I created a jQuery function which converts HTML select boxes into a filter box but I don't want it to do anything to the select boxes if a specific stylesheet is active. Because if the specific stylesheet is active, it means it'll be on a mobile device and I don't want the filter box to work on mobiles, I just want the default select box to show. Commented Jan 27, 2016 at 1:58
  • easier to just use breakpoints as per answer below Commented Jan 27, 2016 at 2:10

1 Answer 1

1

To get the current @media in effect, you can use the new MediaQueryList object in window. It has matchMedia method that you can pass media query like this.

if (window.matchMedia("(min-width: 400px)").matches) {
  /* the viewport is at least 400 pixels wide */
} else {
  /* the viewport is less than 400 pixels wide */
}

You can register a listener instead of poll the query's matchMedia result. This can be done by calling addListener() method like this:

var mql = window.matchMedia("(min-width: 400px)");
mql.addListener(MediaQueryChange);
MediaQueryChange(mql);

// media query has changed
function MediaQueryChange(mq) {

    if (mq.matches) {
        /* the viewport is at least 400 pixels wide */
    }
    else {
        /* the viewport is less than 400 pixels wide */
    }

}
Sign up to request clarification or add additional context in comments.

3 Comments

But is there any way to see all active stylesheets given a resolution?
You get current viewport size. You will know which CSS is in effect.
I guess the issue is if I change the min-width in the CSS, I don't want to have to change it in the JavaScript as well. I just want it to check if a certain stylesheet is active. Is it possible do you think?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.