loading...

A simple way to detect if browser is on a mobile device with Javascript

timhuang profile image Timothy Huang ・1 min read

Sometimes we need a little Javascript code snippet to detect if user use mobile device, the simplest way is detecting its browser user agent.

We use the regular expression test to detect if browser is a mobile device like:

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

demo is on codepen:

https://codepen.io/timhuang/pen/MWKEZMJ

Reference:

https://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device

Discussion

markdown guide