Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active January 25, 2021 07:59
Show Gist options
  • Save LeanSeverino1022/85340fba977be698f82e59dd90a532e5 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/85340fba977be698f82e59dd90a532e5 to your computer and use it in GitHub Desktop.
Detect if using a mobile device #vanillajs

02/2021

Multiple resources suggest using the Navigator userAgent property to detect mobile devices. However you must take into account that maybe it's not 100% reliable and some devices could give you "false" (I haven't found any problem yet though).

You can use either match or test.

There are alos different ways of doing it but I just used what I think is efficient.

You can also make use of simple media query but there are cases you would prefer not to use that method.

#2 using .test might be faster that .match "Use .test if you want a faster boolean check. Use .match to retrieve all matches when using the g global flag." src: https://stackoverflow.com/a/10940138/6713989

💡Currently I think I like solution #2

#1

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)

alert("You're using Mobile Device!!")

#1.5

var isMobile = navigator.userAgent.match(
        /(iPhone|iPod|iPad|Android|webOS|BlackBerry|IEMobile|Opera Mini)/i)

#2


if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
  // true for mobile device  
}else{
  // false for not mobile device
}

#3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment