MEM
MEM

Reputation: 31307

Is there any js version for css media queries? - a use case scenario

When the screen is on a certain width, we wish to hide a button and, instead, allow the wrapper div to be clickable.

That should only happen, however, when:

@media only screen and (min-width:320px) {

While we can easily display:none; and display:block; the button, the issue arrives when we want to remove the surrounding wrapper div (on higher screen sizes), because, if we display: none; the surrounding div, all their inside content will be removed too!

Is there any javascript version of the media query above, that could be reliable cross browser, and cross OS, that one may have, in order to dynamically add and remove the element on certain screen conditions?

Upvotes: 0

Views: 94

Answers (2)

nanobar
nanobar

Reputation: 66355

Yeah check this:

https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia

Syntax

mql = window.matchMedia(mediaQueryString)

Where mediaQueryString is a string representing the media query for which to return a new MediaQueryList object.

Example

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

And a polyfill like this:

https://github.com/paulirish/matchMedia.js/

Old IE:

https://github.com/benschwarz/matchMedia.js/tree/IE7-8

If you just care about a simple check here's how you could do it with jQuery, though it is pretty trivial to do it in plain Javascript too this is just easier because of your old IE requirements:

var timeout;

function onWindowResize() {
    var width = $(window).width();

    if (width <= 480) {
        console.log('small');
    } else if (width <= 767) {
        console.log('medium');
    } else if (width <= 1024) {
        console.log('large');
    } else {
        console.log('xlarge');
    }
}

$(window).resize(function() {
    clearTimeout(timeout);
    timeout = setTimeout(function() {
        onWindowResize();
    }, 50); // Only resize every 50ms - number up to you.
});

Upvotes: 2

Quentin
Quentin

Reputation: 943214

Don't use JS to change the display property on the element directly. Modify the class names that are associated with the element instead.

You can then define display: none or otherwise using a class selector and media queries in your external stylesheet.

Upvotes: 0

Related Questions