Skip to content

Instantly share code, notes, and snippets.

@4ndrej
Created April 27, 2018 10:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save 4ndrej/33ac749d26b93b230269d8f93de7ced3 to your computer and use it in GitHub Desktop.
Save 4ndrej/33ac749d26b93b230269d8f93de7ced3 to your computer and use it in GitHub Desktop.
detect mobile device using javascript
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());
},
none: function() {
return (!isMobile.any());
}
};
@4ndrej
Copy link
Author

4ndrej commented Apr 27, 2018

<script type="text/javascript">
    if (isMobile.any()){
        document.write('Mobile');
        if (isMobile.iOS()){
            document.write('/iOS');
        } else if (isMobile.Android()){
            document.write('/Android');
        } else if (isMobile.BlackBerry()){
            document.write('/BlackBerry');
        } else if (isMobile.Windows()){
            document.write('/Windows');
        } else {
            document.write('/other');
        }
    } else if (isMobile.none()) {
        document.write('non-mobile');
    } else {
        document.write('unknown');
    }
</script>

@4ndrej
Copy link
Author

4ndrej commented Apr 27, 2018

minified (512 bytes):
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()},none:function(){return!isMobile.any()}};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment