Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run some javascript code only on small screen/mobile devices

I am building a vue web app which will be used across all devices. I have some code which I want to get executed only on small devices or mobile. Currently I have that code in a if condition with $(window).width(), like following:

if ($(window).width() <= 768) {
  //My mobile specific code
}

Is there some better way or vue way of doing this?

Edit

For example in one of the component I have:

export default {
  data () {
    return {
      fade: false,
      showFilter: $(window).width() > 768
    }
  },
  components: { PrFilter, Pr },
  created () {
    if ($(window).width() <= 768) {
      bus.$on('pr-changed', () => {
        this.showFilter = false
        this.fade = false
      })
    }
  }
}

in another component, I have:

watch: {
  matchingPr: function (filteredPr) {
    if (filteredPr.length) {
      this.pr = filteredPr[0]
      if ($(window).width() <= 768) {
        bus.$emit('pr-changed')
      }
    }
  }
},
like image 983
Saurabh Avatar asked Sep 14 '26 08:09

Saurabh


2 Answers

you can use

function detectmob() { 
 if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 || navigator.userAgent.match(/Windows Phone/i)
 ){
    return true;
  }
 else {
    return false;
  }
}

navigator.userAgent Method.

like image 92
Parth Ghiya Avatar answered Sep 16 '26 22:09

Parth Ghiya


The best way to achieve this is using the plugin called vue-mediaquery.

https://alligator.io/vuejs/vue-media-queries/

It worked for me.

I hope this helps!

like image 41
Jayesh Dhandha Avatar answered Sep 16 '26 21:09

Jayesh Dhandha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!