Search code examples
javascriptcssmedia-queries

Is it possible to set data in CSS for JS to know certain media queries are applying?


Is there a way for your Javascript to know that a specific CSS media query is applying without duplicating the conditions of the media query in your Javascript? I'm thinking something like the HTML data attribute, but for CSS.

For instance:

CSS

@media (min-width: 94em) {
    .menu{
        -data-break: sidebar-open;
    }
}

JS

if( $('.menu').cssData('break') == 'sidebar-open' ){
     ...
}

I'm trying to have a drawer open on load if the window is at a certain width and a certain media query is applying.

I realize I can do this by using the width in the JS, but I'd like to find a way to do it without duplicating the width variable. I also know I could make the JS conditional on the CSS rules within the media query, but that wouldn't be useful in this circumstance.


Solution

  • While this isn't a nice solution, what you could possibly do is set the content property for some target element.

    @media ...
        #target {
            content: "sidebar-open";
        }
    

    Since the element is not a :before or :after, the content will compute to none for rendering, but you can still read the value with Javascript:

    $('#target').css('content'); //"sidebar-open"