Stopbyte

How to detect Mobile device for an HTML page using Javascript cross-browser?

I am trying to Execute specific Javascript when my HTML page is loaded in a mobile device using Javascript.

What is the best way to do that, preferably some clean method to call like this:

if (isMobileDevice())
{
    // Execute mobile code
} else {
    // Execute Desktop code.
}

I need this method to be Cross Browser.

2 Likes

In my opinion, i Prefer to Detect the hosting device Screen Size, Width mainly. for two reasons:

  1. You cannot identify all the mobile devices in the market (especially Chinese).
  2. Some Tablets behave like Desktops, and others like Phones.

So the only thing that can help you identify the manner to render your pages is checking your device Screen Width, which is not just more accurate but also much easier.

2 Likes

Here is a code to implement what Yep commented. I personally prefer that method too, since you can’t guess all the user agents out there so you can simply rely on width and height (width mainly):

function IsMobileDevice()
{
    if($(window).width() <= 728)
    {
        return true;
    }
    else
    {
        return false;
    }
}

I really highly suggest using the Width & Height instead of detecting which Smartphone device!

2 Likes

you can refer to this website:

download the Javascript code and use it.