How to combine max-width, min-width in matchMedia query?
Asked Answered
C

1

7

I am working with the matchMedia API to determine viewports within javascript, so I can minimize the amount of dom manipulation taking place.

Instead of using display: none everywhere I determine if elements are inserted into the DOM or not with a v-if directive from Vue.

I have set it up like this:

resize() {
    this.mobile = window.matchMedia('(max-width: 767px)').matches;
    this.tablet = window.matchMedia('(max-width: 767px)').matches;
    this.desktop = window.matchMedia('(min-width: 992px)').matches;
}

The mobile matchmedia query is fine but how do I determine exactly what is tablet size? I am wondering if I can combine max-width and min-width values within the matchMedia query.

Of course I could do something like this:

resize() {
    this.mobile = window.matchMedia('(max-width: 767px)').matches;
    this.desktop = window.matchMedia('(min-width: 992px)').matches;
    this.tablet = !this.mobile && !this.desktop;
}

I am wondering is this is properly set up like this though.

Cinderellacindi answered 25/7, 2017 at 8:20 Comment(0)
W
25

Just combine the media queries as you would do in CSS:

this.tablet = window.matchMedia('(min-width:767px) and (max-width: 992px)');

Weese answered 25/7, 2017 at 8:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.