6

What is the simplest way to detect if the device is a mobile device with javascript?

I was thinking checking if the height is less than or equal to the iPhone's browser viewport height. Speaking of which, what is the iPhone's or a common viewport height for mobile devices?

I was having some troubles with window.height; in javascript as it was coming back undefined, however?

Anyone know how do best and simply detect if the browser is an mobile device with javascript?

3

1 Answer 1

20

This is what I have for my hobby project:

var Environment = {
    //mobile or desktop compatible event name, to be used with '.on' function
    TOUCH_DOWN_EVENT_NAME: 'mousedown touchstart',
    TOUCH_UP_EVENT_NAME: 'mouseup touchend',
    TOUCH_MOVE_EVENT_NAME: 'mousemove touchmove',
    TOUCH_DOUBLE_TAB_EVENT_NAME: 'dblclick dbltap',

    isAndroid: function() {
        return navigator.userAgent.match(/Android/i);
    },
    isBlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    isIOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    isOpera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    isWindows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    isMobile: function() {
        return (Environment.isAndroid() || Environment.isBlackBerry() || Environment.isIOS() || Environment.isOpera() || Environment.isWindows());
    }
};

Your solution about using dimension is not a good solution. It relies on the actual device dimension and many other variables.

Sign up to request clarification or add additional context in comments.

3 Comments

This looks good! Thank you for sharing. But how would I implement or use it? For example do I just do if(isMobile()){ //myCodeHere }
what is the difference between your code and this or is this just a more concise version? if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ){ // some code.. }
The difference is that my code is more usuable and more readable. Whenever you want to detect mobile environment, you would have to do write that long if statement and could be error prone, with mines, its just Environment.isMobile() function call. To use it, you can include that code inside one of your javascript file. And then simple do if(Environment.isMobile()){ ... }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.