Detect screen size (xs, sm, md, etc) via javascript?
-
I see there are all these fabulous css helpers for showing things or not based on the screen size (xs, sm, md, etc) https://quasar-framework.org/components/visibility.html#Window-Width-Related and these work for most of my use cases, but i came across a case where I need to set a boolean variable based on the screen size.
For example I want my
q-layout-drawer
to render open on page load for anything greater than sizemd
, but i want it to render closed on page load for small screens.Is there a way I can set a variable in
mounted ()
by detecting the screen size? -
@toymachiner62
check this out https://quasar-framework.org/components/window-resize-observable.html, then use a boolean v-model for your q-layout-drawer<q-layout-drawer v-model="drawerState" ..
... methods: { onResize (size) { console.log(size) // { // width: 1200 // width of viewport (in px) // height: 920 // height of viewport (in px) // } if (size.width > 992) { //md is 992px this.drawerState = true } } ...
-
I just came across the
screen
plugin which seems like it would solve what i’m looking for! https://quasar-framework.org/components/screen-plugin.html -
I stumbled upon the same question and solved it as documented by the Quasar team:
Instead of using this css:
@media screen and (min-width: 599px) { .q-footer { display: none; } }
I now do this in my template:
<div class="lt-sm">Small display</div> <div class="gt-xs">Large display</div>
Another option if you can’t use css classes is using
$q.screen
in your<script>
section of a component:methods: { setSomething() { if (this.$q.screen.width > 1023) { console.log('screen large') } else { console.log('screen small') } }, }, watch: { "$q.screen.width"() { this.setSomething() } }
If it’s not in a component and you want to know the screen size on the startup of your app for example you can use the following:
import { Screen } from 'quasar' Screen.lt.sm ? console.log('screen small') : console.log('screen large')
I hope this helps someone.
-
console.log(this.$q.screen)
{ xs: false, sm: false, md: false, lg: true, xl: false, sizes: { sm: 600, md: 1024, lg: 1440, xl: 1920 } }
-
This post is deleted!