简体   繁体   中英

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')
      }
    }
  }
},

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.

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!

You can check for condition and load JS as per necessity.

<script>
if (screen && screen.width > 480) {
  document.write('<script type="text/javascript" src="foo.js"><\/script>');
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM