Detect if is mobile with Javascript, read user agent

How to detect if your user is using a mobile device in Javascript? You can do it by checking the…

Novembre 5, 2013

How to detect if your user is using a mobile device in Javascript? You can do it by checking the user agent, that is the “signature” of the browser. When a browser request a page it introduces himself by telling which browser is. This signature is accessible by php on the server, but also by Javascript on the client.

Read User Agent in Javascript:

function isMobile () {
   if( navigator.userAgent.match(/iphone/i) ||
   navigator.userAgent.match(/ipad/i) ||
   navigator.userAgent.match(/android/i) ||
   navigator.userAgent.match(/blackberry/i) ||
   navigator.userAgent.match(/android/i)
   ) {
      return true;
   }
   return false;
}

This code search the user agent string for matching for keyword “ipad”, “iphone”, “blackberry” and “android”. If there is an occurence return true, else return false;

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Recommended

The Quantcast CMP broke my sites

A javascript error in CMP blocks my site.

Maggio 19, 2023

Scroll to DIV by ID without jQuery

Use scrollIntoView instead of jQuery animate.

Dicembre 16, 2022

React links

Collection of links and notes while approaching React.js, next.js and related topics.

Dicembre 14, 2022

Add Internet Explorer class to body to detect old browser

When you have clients that still uses an old browser, you need to handle it. This javascript function detects the…

Febbraio 27, 2017

Modify list counter in :before pseudo class with jQuery using start attribute

Suppose you have two ordered list ol tags, and the second one has a start attribute. You also have in…

Aprile 20, 2016