7

Here's my snippet for detecting a mobile display based on the screen size. You can force the site to stay in desktop-mode by adding a forceDesktop param to the URL.

I`m new to jquery so if you have suggestions, please comment.

Credits go to brandonjp: How can I get query string values in JavaScript?

        <script>
            $.urlParam = function(name, url) {
                if (!url) {
                    url = window.location.href;
                }
                var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
                if (!results) { 
                    return undefined;
                }
                return results[1] || undefined;
            }
            window.onload = function() {
                var forceDesktop = $.urlParam('forceDesktop');
                if (!forceDesktop) {
                    if ( $(window).width() < 639) {   
                        var url = "http://m.mysite.com/";    
                        $(location).attr('href',url);
                    }
                }
            };
        </script>
Community
  • 1
  • 1
Sacha Vorbeck
  • 327
  • 1
  • 2
  • 14
  • 1
    I know this post is more than 2 years old but it should really be on [codereview](http://codereview.stackexchange.com) instead of here... – Ortund Feb 07 '17 at 10:04

4 Answers4

6

why not this?

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    window.location = "http://m.mysite.tld/"; 
}
John Slegers
  • 45,213
  • 22
  • 199
  • 169
Patrick
  • 69
  • 1
  • 2
4

Actually, I believe that it is important to detect mobile from window width.

So here is the way that I am using.

function detectmob() {
   if(window.innerWidth <= 800 || window.innerHeight <= 600) {
     return true;
   } else {
     return false;
   }
}

if (detectmob()){
top.location.href="mobile";
}
Ahmet Can Güven
  • 5,392
  • 4
  • 38
  • 59
  • 2
    I think you need `OR`, not `AND`, because many phone screens are 720 or 800px tall while being only 480px wide. – pawel Oct 30 '14 at 10:06
3

best way is

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) )     
{
   var url = "http://m.mysite.com/";    
   $(location).attr('href',url);

}

For more Here

Community
  • 1
  • 1
Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73
  • Yes its also valid one `location.replace("http://m.mysite.com/")` But if He wants to use url for other purpose then he can cache in `var`. – Pratik Joshi Oct 30 '14 at 10:00
3

If you're going to use some form of browser-sniffing rather than feature detection via something like Modernizr, your best bet is to grab some script from http://detectmobilebrowsers.com/ rather than use home-grown / incomplete scripts pasted here and there.

Ben
  • 7,548
  • 31
  • 45