3 ways to detect mobile device in jQuery

When working with magento, I usually meet the problem with mobile device. The thing is there are some javascript need to run different in mobile device and I don’t know my extension will be install in desktop theme or mobile theme and which device it is working in. So I found the very good way to detect the device and hope it will save you a little time with 3 ways to detect mobile device in jQuery.

Detect Mobile Using jQuery

1. Detect Mobile Device with simple javascript

Even though your code don’t include jQuery, you still have chance to detect mobile device with very simple code

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // You are in mobile browser
}

or you can combine them both to make it more accessible through jQuery…

$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));

2. isMobile function

For the code reuse later on you can use this object, you can save it as a js file for your source code library

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

As you see, it ‘s quite simple to use

if(isMobile.any()) {
   // It is mobile
}

3. TouchEvent to detect mobile device

Maybe the simplest way to detect mobile device is not base on the browser name but base on the event what browser support. Let ‘s use these code line to figure out

function isMobile() {
  try{ document.createEvent("TouchEvent"); return true; }
  catch(e){ return false; }
}

I am pretty sure you knew how to use it, unless just leave me a comment.

References: http://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-handheld-device-in-jquery

6 comments

  1. The second way is the best I think so, it work for my project by jquery mobile. But I am wondering if it catch all of situations?

  2. It ‘s quite easy to do this work, thanks for a great tips to detect mobile browser. Do you make it as PHP lib?

Leave a Reply

Your email address will not be published. Required fields are marked *

*