How to detect mobile devices using Javascript?

| | 1 min read

We need to develop websites for a variety of mobile devices along with regular desktop versions. To do this effectively we need to detect the mobile devices when they access the website which can be done through Javascript. Read on to know how to detect mobile devices using Javascript

We can detect mobile devices using PHP. However if the site is statically cached and the site has a different theme for desktop and mobile browsers, PHP code will not be executed and anonymous users of the site will get the theme that was loaded for the first time, irrespective of the device they are using. To fix this, we implement the user redirection or theme switching code within JavaScript. This JavaScript code is added to the header of all page templates. So the script gets executed before loading the page and the page is redirected or reloaded, depending upon the device used to render the page.

Implementation of theme switching using JavaScript.

Check out the sample code and the comment for how each line works.

<script type="text/javascript">
// Checking for the devices.
// You can add more devices here.
// Here we check if the user agent is a known mobile devices or not.
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
  // Here is the code to redirect user to mobile link.
  window.location = "";

Take care to place the code at the header section of the HTML page so that the page gets redirected before the page gets loaded.